Creating Responses in Laravel

Strings and Arrays

Laravel have many different ways to return responses.The framework will automatically convert the string into a full HTTP response.

Route::get('/', function () {
    return 'Howtowebcode';
});

Response Objects

In Laravel you will be returning full Illuminate\Http\Response instances or views.

Route::get('demo', function () {
    return response('howtowebcode', 200)
            ->header('Content-Type', 'text/plain');
});

Attaching Cookies To Responses

return response($content)
                ->header('Content-Type', $type)
                ->cookie('name', 'value', $minutes);

Redirects

Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL.

Route::get('dashboard', function () {
    return redirect('howtowebcode/dashboard');
});

In Laravel you may sometimes wish to redirect user to their previous location like when a submitted form is invalid. In Laravel you may using the global back helper function.

Route::post('user/profile', function () {

    return back();
});

Redirecting To Named Routes

It generate a RedirectResponse to a named route you may use the route method.

return redirect()->route('home');

If your route has parameters you pass them as the second argument to the route method

return redirect()->route('profile', ['id' => 1]);

Redirecting With Flashed Session Data

You Redirect Response instance and flush data to session in single fluent method chain.

Route::post('user/login', function () {
    return redirect('home')->with('status', 'success');
});

After user is redirected you may display the flashed message from session.

<?php
    @if (session('status'))
        <div class="alert alert-success">
            {{ session('status') }}
        </div>
    @endif
?>