response


1. Create Response

String&Array

All routes and controllers will return a 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. The framework will convert this string into a complete HTTP response:

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

In addition to returning strings from routes or controllers, you can also return arrays. The framework will automatically convert the array into a JSON response:

 Route::get('/', function () { return [1, 2, 3]; });
Note: Do you know that Eloquent collection can also be returned from route or controller? This will also be automatically converted to JSON. Try it.

Response object

Usually, we do not simply return strings and arrays from routing actions. In most cases, we will return a complete Illuminate\Http\Response Instance or view.

Return a complete Response The instance allows you to customize the HTTP status code and header information of the response. Response Instance inherited from Symfony\Component\HttpFoundation\Response Class, which provides a series of methods for creating HTTP responses:

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

Add Response Header

Most response methods can be called in the form of method chains, so that the response can be constructed smoothly (flow interface mode). For example, you can use the 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 cookie Method can easily add cookies to the response. For example, you can use cookie Method to generate a cookie and add it to the response instance:

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

cookie The method can also receive more optional parameters that are less frequently used. Generally speaking, these parameters are similar to those provided by PHP natively setcookie The purpose and significance of the method are similar:

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

Cookies&Encryption

By default, the cookies generated by the Larravel framework are encrypted and signed to prevent tampering on the client side. If you want a specific subset of cookies to be unencrypted during generation, you can use app/Http/Middleware Middleware under directory App\Http\Middleware\EncryptCookies Provided $except Property to exclude these cookies:

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

2. 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 (because this function uses Session , before using this method, ensure that the route uses 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 Redirector All methods on the instance. For example, to generate a RedirectResponse To a named 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', ['id'=>1]);

Filling parameters with Eloquent model

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]);

If you want to customize the default value (id by default) in this routing parameter, you need to override the getRouteKey method:

 /** * Get the value of the model's route key. * * @return mixed */ public function getRouteKey() { return $this->slug; }

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 ', ['id'=>1]);

Redirection with one-time session data

Redirect to a new URL and Store data to a one-time session Is usually completed at the same time. For convenience, you can create a RedirectResponse The instance then stores the data to the session on the same method chain action It is particularly convenient to store status information later:

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

Of course, after the user redirects to the new page, you can Session And display these one-time information, for example, using Blade syntax The implementation is as follows:

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

3. 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 contract This contract provides some useful methods to generate responses.

View Response

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, 200) ->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 response

json Method will automatically Content-Type Header set 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']) ->withCallback($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 download requires that the downloaded file have an ASCII file name.

File Response

file The method can be used to display files, such as pictures or PDFs, directly in the user's browser without downloading. The method receives the file path as the first parameter and the header array as the second parameter:

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

4. Response Macro

If you want to define a customized response that can be reused in multiple routes and controllers, you can use Response On the facade macro method. For example, in a Service Provider Of boot The code in the method is as follows:

 <? php namespace App\Providers; use Illuminate\Support\Facades\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, the closure function as the second parameter, and the closure of the response macro ResponseFactory Implementation class or auxiliary function response The macro name is executed when called in:

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

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: request

>>Next: view