Skip to content

Instantly share code, notes, and snippets.

@bonniss
Created October 28, 2019 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bonniss/5cefc07c76ea6dbd320c4efbc73f419f to your computer and use it in GitHub Desktop.
Save bonniss/5cefc07c76ea6dbd320c4efbc73f419f to your computer and use it in GitHub Desktop.
A quick guide on Laravel Responses, reference to official docs

Laravel Reponses

Ref: https://laravel.com/docs/5.8/responses

Creating Responses

String or array

All routes and controllers should return a response to be sent back to the user's browser. The most basic is returning a string from a route or controller, which will be converted automatically into a full HTTP response.

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

You may return arrays, which will be converted into JSON response.

Route::get('/', function() {
    return [1, 2, 3];
});

Reponse Objects

Typically, you will be returning full Illuminate\Http\Response instances or views.

Returning a full Response instance allows you to customize the response's HTTP status code and headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, which provides a variety of methods for building HTTP responses.

/* Keep in mind that most response methods are chainable */
/* Adding headers to response */
Route::get('home', function() {
    return response('Hello World', 200)
        ->header('Content-Type', 'text/plain');
});

/* Adding multiple headers to response */
return response($content)
        ->header('Content-Type', $type)
        ->header('X-Header-One', 'Header Value')
        ->header('X-Header-Two', 'Header Value');

/* You can specify an array of headers to add to response */
return response($content)
        ->withHeaders([
            'Content-Type' => $type,
            'X-Header-One' => 'Header Value',
            'X-Header-Two' => 'Header Value',
        ]);

Cache Control Middleware

Laravel includes a cache.headers middleware, which may used to quickly set the Cache-Control header for a group of routes. If etag is specified in the list of directives, an MD5 hash of the response content will automatically be set as the ETag identifier:

Route::middleware('cache.headers:public;max_ageL2628000;etag')->group(function() {
    // Routes which are applied caching
    Route::get('terms', function() {
        //...
    });

    Route::get('privacy', function() {
        //...
    });
});

Adding cookies to responses

/* attach cookie on a single response */
return response($content)
        ->header('Content-Type', $type)
        ->cookie('name', 'value', $minutes);

/* "queue" cookies for attachment to the outgoing response before it is send to the browser */
Cookie::queue(Cookie::make('name', 'value', $minutes));

/* all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. You can disable encryption for a subset of cookies. */
// In app/Http/Middleware use App\Http\Middleware
protected $except = [
    'cookie_name',
];

Redirects

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

  • There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:

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

Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group or has all of the session middleware applied.

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

    return back()->withInput();
});

When you call the redirect helper with no params, an instance of Illuminate\Routing\Redirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route.

/* Redirect to a named route */
// A named route
Route::get('/login', function() {

})->name('login');

// Inside another route
return redirect()->route('login');

// If the route has params, pass them as the second argument
return redirect()->route('login', ['id' => 1]);

/* Via Eloquent model */
// If you are redirecting to a route with an "ID" parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically.
// For a route with the following URI: profile/id
return redirect()->route('profile', [$user]);

// If you would like to customize the value that is placed in the route parameter, you should override the `getRouteKey` method on the Eloquent model
public function getRouteKey() {
    return $this->slug;
}

/* Redirect to Controller Actions */
// Pass the controller and action to the "action" method of the Redirector
// You do not need to specify the full namespace to the controller
return redirect()->action('HomeController@index');

// With paramater
return redirect()->action(
    'UserController@profile', ['id' => 1]
);

/* Redirect to external domains */
return redirect()->away('htpps://www.google.com');

Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session.

Route::post('user/profile', function() {
    // Update the user's profile...

    return redirect('dashboard')->with('status', 'Profile updated!!');
});

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

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

Other Response Types

The response helper may be used to generate other types of response instances. When the response helper is called without arguments, an implementation of the Illuminate\Contracts\Routing\ResponseFactory contract is returned.

View Response

If you need control over the response's status and headers but also need to return a view as the response's content, you should use the view method.

return response()
        ->view('hello', $data, 200)
        ->header('Content-Type', $type);

JSON Response

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function.

return response()->json([
    'name'=>'Duy Trung',
    'age'=>90
]);

// create JSONP response
return response()
    ->json[
        'name'=>'Duy Trung',
        'age'=>90
    )->withCallback($request->input('callback'));

File Downloads

The download method may be used to generate a response that forces the user's browser to download the file at the given path.

return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

return response()->download($pathToFile)->deleteFileAfterSend();
// ** Note: the file being downloaded must have an ASCII file name.

Streamed Downloads

Sometimes you wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the streamDownload method to obtain the goal.

return response()->streamDownload(function () {
    echo GitHub::api('repo')
                ->contents()
                ->readme('laravel', 'laravel')['contents'];
}, 'laravel-readme.md');

File Response

Sometimes you want to display a file, such as an image of PDF, directly in the browser instead of initiating a download.

return response()->file($pathToFile);

// With headers
return response()->file($pathToFile, $headers);

Response Macros

If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment