HTTP Response


1. Basic response

All routes and controllers will return some response sent to the user's browser. Larvel provides many different ways to return the response. The most basic response is to return a simple string from the route or controller:

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

The given string will be automatically converted into an HTTP response by the framework.

Response object

However, most routing and controller actions return a complete Illuminate\Http\Response Instance or view, returning a complete Response instance allows you to customize the HTTP status code and header information of the response. Response instance inherits from Symfony\Component\HttpFoundation\Response Class, which provides a series of methods for creating HTTP responses:

 use Illuminate\Http\Response; Route::get('home', function () { return (new Response($content, $status)) ->header('Content-Type', $value); });

For convenience, you can also use auxiliary functions response

 Route::get('home', function () { return response($content, $status) ->header('Content-Type', $value); });
Note: To view the complete list of Response methods, please move to the corresponding API documentation as well as Symfony API documentation

Add Response Header

Most of the response methods can be called in the form of method chain, so that the response can be constructed smoothly (flow interface mode). For example, you can use header Method to add a series of response headers:

 return response($content) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value');

Or you can use withHeaders Method to specify the header information array and add it to the response:

 return response($content) ->withHeaders([ 'Content-Type' => $type, 'X-Header-One' => 'Header Value', 'X-Header-Two' => 'Header Value', ]);

Add Cookies to Response

Use the auxiliary function of the response instance cookie Cookies can be easily added to responses:

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

cookie Method receives additional optional parameters to allow more customization of cookie properties:

 ->cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)

By default, the cookies generated by the Larravel framework are encrypted and signed to avoid being tampered with on the client side. If you want to make a specific cookie subset unencrypted when generating, you can use middleware App\Http\Middleware\EncryptCookies Of $except Property to exclude these cookies:

 /** *Cookies names that do not need to be encrypted * * @var array */ protected $except = [ 'cookie_name', ];

2. Other response types

auxiliary function response It can be easily used to generate other types of response instances response Will return when Illuminate\Contracts\Routing\ResponseFactory An implementation class instance of a contract that provides some useful methods to generate responses.

view

If you need to control the response status and response header and return a view as the response content, you can use view method:

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

Of course, if you don't need to pass custom HTTP status codes and headers, you just need to simply use global auxiliary functions view OK.

JSON

json Method will automatically set the Content Type header to application/json , and use PHP functions json_encode Method to convert the given array to JSON:

 return response()->json(['name' => 'Abigail', 'state' => 'CA']);

If you want to create a JSONP response, you can json Call after method setCallback method:

 return response()->json(['name' => 'Abigail', 'state' => 'CA']) ->setCallback($request->input('callback'));

File download

download Method is used to generate a response that forces a user's browser to download a file of a given path. download The method accepts the file name as the second parameter, which determines the display name of the file downloaded by the user. You can also pass the HTTP header information to the method as the third parameter:

 return response()->download($pathToFile); return response()->download($pathToFile, $name, $headers);
Note: The Symfony HttpFoundation class that manages file downloads requires an ASCII file name for the downloaded file.

3. Redirect

Redirect response is Illuminate\Http\RedirectResponse Class, which contains the necessary header information to redirect the user to another URL. There are many ways to generate RedirectResponse For example, the simplest way is to use global auxiliary functions redirect

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

Sometimes you want to redirect the user to the location of the last request. For example, after the form is submitted and the verification fails, you can use auxiliary functions back Return to the previous URL (make sure the route is used before using this method web The middleware group or both use session Middleware):

 Route::post('user/profile', function () { //Verify Request return back()->withInput(); });

Redirect to Named Route

If you call the redirect Method, a Illuminate\Routing\Redirector Instance, and then you can call any method on that instance. For example, to generate a RedirectResponse To name a route, you can use the route method:

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

If there is a parameter in the route, it can be passed to the route method:

 // For a route with the following URI: profile/{id} return redirect()->route('profile', [1]);

If you want to redirect to a route with ID parameters (Eloquent model binding), you can pass the model itself, and the ID will be automatically resolved:

 return redirect()->route('profile', [$user]);

Redirect to Controller Action

You can also generate redirect to controller actions by simply passing the controller and action name to action Method. Remember, you don't need to specify the full namespace of the controller, because Larave's RouteServiceProvider The default controller namespace will be set automatically:

 return redirect()->action(' HomeController@index ');

Of course, if the controller route requires parameters, you can pass the parameters as the second parameter to action method:

 return redirect()->action(' UserController@profile ', [1]);

Redirection with one-time session data

Redirection to a new URL and storing data in a one-time session are usually completed at the same time. For convenience, you can create a RedirectResponse The instance then stores the data to the session in the same method chain. This method is particularly convenient for storing status information after the action:

 Route::post('user/profile', function () { //Update User Properties return redirect('dashboard')->with('status', 'Profile updated!'); });

Of course, after the user redirects to a new page, you can retrieve and display these one-time information from the session. For example, use the Blade syntax to achieve the following:

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

4. Response Macro

If you want to define a custom response and reuse it in multiple routes and controllers, you can use Illuminate\Contracts\Routing\ResponseFactory Implementation class or Response On the facade macro method.

For example, write the following code in the boot method of a service provider:

 <? 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)); }); } }

macro The method receives the response name as the first parameter, and the closure function as the second parameter, macro The closure of is in the ResponseFactory Implementation class or auxiliary function response Called in macro Name is executed when:

 return response()->caps('foo');

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: HTTP Request

>>Next: view