HTTP Responses
Basic Responses
Of course, all routes and controllers should return some kind of response to be sent back to the user's browser. Laravel provides several different ways to return responses. The most basic response is simply returning a string from a route or controller:
Route::get('/', function () {
return 'Hello World';
});
The given string will automatically be converted into an HTTP response by the framework.
Response Objects
However, for most routes and controller actions, you will be returning a full Illuminate\Http\Response
instance or a view. 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, providing a variety of methods for building HTTP responses:
use Illuminate\Http\Response;
Route::get('home', function () {
return (new Response($content, $status))
->header('Content-Type', $value);
});
For convenience, you may also use the response
helper:
Route::get('home', function () {
return response($content, $status)
->header('Content-Type', $value);
});
Note: For a full list of available
Response
methods, check out its API documentation and the Symfony API documentation.
Attaching Headers To Responses
Keep in mind that most response methods are chainable, allowing for the fluent building of responses. For example, you may use the header
method to add a series of headers to the response before sending it back to the user:
return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
Or, you may use the withHeaders
method to specify an array of headers to be added to the response:
return response($content)
->withHeaders([
'Content-Type' => $type,
'X-Header-One' => 'Header Value',
'X-Header-Two' => 'Header Value',
]);
Attaching Cookies To Responses
The cookie
helper method on the response instance allows you to easily attach cookies to the response. For example, you may use the cookie
method to generate a cookie and attach it to the response instance:
return response($content)
->header('Content-Type', $type)
->cookie('name', 'value');
The cookie
method accepts additional optional arguments which allow you to further customize your cookie's properties:
->cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
Alternatively, you may use the queue
method on the Cookie
facade to create a cookie that will be automatically added to the outgoing response:
<?php
namespace App\Http\Controllers;
use Cookie;
use App\Http\Controllers\Controller;
class DashboardController extends Controller
{
/**
* Show the application dashboard.
*
* @return Response
*/
public function index()
{
Cookie::queue('saw_dashboard', true, 15);
return view('dashboard');
}
}
In this example, the saw_dashboard
cookie will automatically be added to the outgoing response without forcing you to manually attach the cookie to a specific response instance.
Cookies & Encryption
By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. If you would like to disable encryption for a certain subset of cookies generated by your application, you may use the $except
property of the App\Http\Middleware\EncryptCookies
middleware:
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
'cookie_name',
];
Other Response Types
The response
helper may be used to conveniently 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. This contract provides several helpful methods for generating responses.
View Responses
If you need control over the response status and headers, but also need to return a view as the response content, you may use the view
method:
return response()
->view('hello', $data)
->header('Content-Type', $type);
Of course, if you do not need to pass a custom HTTP status code or custom headers, you should simply use the global view
helper function.
JSON Responses
The json
method will automatically set the Content-Type
header to application/json
, as well as convert the given array into JSON using the json_encode
PHP function:
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
If you would like to create a JSONP response, you may use the json
method in addition to setCallback
:
return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($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. The download
method accepts a file name as the second argument to the method, which will determine the file name that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
Note: Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII file name.
File Responses
The file
method can be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
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 method:
Route::get('dashboard', function () {
return redirect('home/dashboard');
});
Sometimes you may wish to redirect the user to their previous location, for example, after a form submission that is invalid. You may do so by using the global back
helper function. However, make sure the route using 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();
});
Redirecting To Named Routes
When you call the redirect
helper with no parameters, 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, you may use the route
method:
return redirect()->route('login');
If your route has parameters, you may pass them as the second argument to the route
method:
// For a route with the following URI: profile/{id}
return redirect()->route('profile', ['id' => 1]);
If you are redirecting to a route with an "ID" parameter that is being populated from an Eloquent model, you may simply pass the model itself. The ID will be extracted automatically:
return redirect()->route('profile', [$user]);
Redirecting To Controller Actions
You may also generate redirects to controller actions. To do so, simply pass the controller and action name to the action
method. Remember, you do not need to specify the full namespace to the controller since Laravel's RouteServiceProvider
will automatically set the default controller namespace:
return redirect()->action('[email protected]');
Of course, if your controller route requires parameters, you may pass them as the second argument to the action
method:
return redirect()->action('[email protected]', ['id' => 1]);
Redirecting With Flashed Session Data
Redirecting to a new URL and flashing data to the session are typically done at the same time. So, for convenience, you may create a RedirectResponse
instance and flash data to the session in a single method chain. This is particularly convenient for storing status messages after an action:
Route::post('user/profile', function () {
// Update the user's profile...
return redirect('dashboard')->with('status', 'Profile updated!');
});
Of course, after the user is redirected to a new page, you may retrieve and display the flashed message from the session. For example, using Blade syntax:
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
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 or the implementation of Illuminate\Contracts\Routing\ResponseFactory
.
For example, from a service provider's boot
method:
<?php
namespace App\Providers;
use Response;
use Illuminate\Support\ServiceProvider;
class ResponseMacroServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Response::macro('caps', function ($value) {
return Response::make(strtoupper($value));
});
}
}
The macro
function accepts a name as its first argument, and a Closure as its second. The macro's Closure will be executed when calling the macro name from a ResponseFactory
implementation or the response
helper:
return response()->caps('foo');