response
- String & Array
- Response Object
- Add response header
- Cache Control Middleware
- Add Cookies to Response
- Cookies & Encryption
- Redirect
- Redirect to named route
- Jump to external domain name
- ##Other response types
- View response
- JSON response
- File download
- Stream download
- File Response
- Response Macro
HTTP response
## Create responseString & ArrayAll routes and controllers will return a response sent to the user's browser after processing the business logic. Laravel provides a variety of There are different ways to return the response. The most basic response is to return a simple string from the route or controller. The framework will automatically convert this string into a complete HTTP response:Route::get('/', function () { return 'Hello World'; });
In addition to returning the response from the route or controller In addition to returning strings, controllers can also return arrays. The framework will automatically convert the array into a JSON response:Route::get('/', function () { return [1, 2, 3]; });
{tip} Did you know you can also return Eloquent collections from routes or controllers? They are also automatically converted into JSON responses.
Response objectUsually, we don’t just simply return strings and arrays from routing actions, in most cases, a completeIlluminate\Http\Response
Returns a completeInstance or view.
Response
instance allowing you to customize the HTTP status code and response header information of the response.
ResponseInstances inherit from the
Symfony\Component\HttpFoundation\Responseclass, which provides various methods for constructing HTTP responses:
Route::get('home', function () { return response('Hello World', 200) ->header('Content-Type', 'text/plain'); });
Add response headersMost response methods are chainable, making the process of creating response instances more readable. For example, you can use theheader
method to add a series of header information to the response before it is returned to the user:
return response($content) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value');
Alternatively, you can use thewithHeaders
method to specify Array of headers to add to the response:
return response($content) ->withHeaders([ 'Content-Type' => $type, 'X-Header-One' => 'Header Value', 'X-Header-Two' => 'Header Value', ]);
Cache Control Middleware
Laravel has a built-in
cache.headers
middleware that can be used to quickly setCache-Control
header information for routing groups. Ifetag
is declared in the directive set, Laravel will automatically set the ETag identifier to the MD5 hash of the response content:Route::middleware('cache.headers:public;max_age=2628000;etag')->group(function() { Route::get('privacy', function () { // ... }); Route::get('terms', function () { // ... }); });
Adding Cookies to a Response
You can easily add cookies to a response using the
cookie
method on the response. For example, you can generate a cookie and easily attach it to the response using thecookie
method like this: Thereturn response($content) ->header('Content-Type', $type) ->cookie('name', 'value', $minutes);
cookie
method also accepts some less frequently used parameters. Generally, these parameters have the same purpose and meaning as the parameters of the native PHP setcookie method:->cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
Alternatively, you can use the
Cookie
facade "queue",Cookie
Attached to the application's outgoing response. Thequeue
method accepts aCookie
instance or the parameters required to create aCookie
instance. These cookies are appended to the outgoing response before being sent to the browser:Cookie::queue(Cookie::make('name', 'value', $minutes)); Cookie::queue('name', 'value', $minutes);
Cookies & Encryption
By default, all cookies generated by Laravel are encrypted and signed and therefore cannot be modified or read by the client. If you want some cookies generated by the application to not be encrypted, you can use the
App\Http\Middleware\EncryptCookies
middleware in theapp/Http/Middleware
directory. $exceptProperties:
/** * 不需要被加密的cookies名称 * * @var array */ protected $except = [ 'cookie_name', ];
RedirectRedirect response isIlluminate\Http An instance of the \RedirectResponse
class and contains the header information required to redirect the user to another URL. Laravel provides several methods for generating
RedirectResponseinstances. The simplest method is to use the global helper function
redirect:
Route::get('dashboard', function () { return redirect('home/dashboard'); });
Sometimes you may want to redirect the user to a previous location, such as when the submitted form is invalid. At this time you can use the global helper functionback
to perform this operation. Since this feature leverages session control, please ensure that the route calling the
backfunction uses the
webmiddleware group or all Session middleware:
Route::post('user/profile', function () { //验证请求 return back()->withInput(); });
Redirect to a named route
If you call the helper function
redirect
without parameters, theIlluminate\Routing\Redirector
instance will be returned. This instance allows you to call any method onRedirector
. For example, to generate aRedirectResponse
for a named route, you can use theroute
method:return redirect()->route('login');
If there are parameters in the route, you can pass them as the second parameter to
route
Method:// 对于具有以下 URI 的路由: profile/{id} return redirect()->route('profile', ['id' => 1]);
Fill the parameters through the Eloquent model
If you want to redirect to a route that uses the "ID" parameter filled in from the Eloquent model, you can simply Pass the model itself. The ID will be automatically extracted:
//对于具有以下 URI 的路由: profile/{id} return redirect()->route('profile', [$user]);
If you want to customize the default parameter name in this route parameter, you need to override the
getRouteKey
method on the model instance:/** * 获取模型的路由键 * * @return mixed */ public function getRouteKey(){ return $this->slug; }
Jump to controller Action
You can also generate a jump to controller action. To do this, just pass the name of the controller and action to the
action
method. Remember, you don't need to pass the full namespace of the controller, Laravel'sRouteServiceProvider
will automatically set it to the namespace of the base controller:return redirect()->action('HomeController@index');
If the controller route requires parameters, you can Use it as the second parameter of the
action
method:return redirect()->action( 'UserController@profile', ['id' => 1] );
Jump to external domain name
Sometimes you need to jump to a domain name outside the application. This is achieved by calling the
away
method, which creates aRedirectResponse
instance without any additional URL encoding, validity checksum checking:return redirect()->away('https://www.google.com');
Jump with session value transferred
It is very common to jump to a new URL and transfer data to the session at the same time. This is usually done after successfully executing an action and sending a message to the session. For convenience, you can create a
RedirectResponse
instance and transfer the data to the session in the chain method call:Route::post('user/profile', function () { // Update the user's profile... return redirect('dashboard')->with('status', 'Profile updated!'); });
After the user jumps, the transferred data in the session can be displayed. For example, use Blade syntax:
@if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif
Other response types
response
Assistant can be used Used to generate other types of response instances. When theresponse
helper is also called with parameters, an implementation of theIlluminate\Contracts\Routing\ResponseFactory
contract is returned. This contract provides several methods for generating responses:View response
If you need to return the view as the response content and control the response status and header information, you need to call the
view
method:return response() ->view('hello', $data, 200) ->header('Content-Type', $type);
If not You need to pass custom HTTP status codes and custom header information, and you can also use the global
##JSON responseview
helper function.json
automatically changes
Content-TypeThe header information is set to
application/json, and the given array is converted to JSON using PHP's
json_encodefunction:
return response()->json([ 'name' => 'Abigail', 'state' => 'CA' ]);
If you want to create a JSONP response, you can Combined with thewithCallback
method, use the
jsonmethod:
return response() ->json(['name' => 'Abigail', 'state' => 'CA']) ->withCallback($request->input('callback'));
##File download# The##download
method can be used to generate a response that forces the user's browser to download a file at a given path.download
The method file name is used as its second parameter, which will be used as the file name of the file downloaded by the user. Finally, you can pass an array of HTTP headers as its third parameter:
return response()->download($pathToFile); return response()->download($pathToFile, $name, $headers); return response()->download($pathToFile)->deleteFileAfterSend();
{note} The Symfony HttpFoundation used to manage file downloads requires that downloaded files have an ASCII file name.
Streaming Download Sometimes you may want to convert the string response of a given operation into a download response without writing it to disk. At this time, you can use the
streamDownload
method. This method accepts a callback, a filename, and an optional array of headers as parameters:return response()->streamDownload(function () { echo GitHub::api('repo') ->contents() ->readme('laravel', 'laravel')['contents']; }, 'laravel-readme.md');
file
The method is used to display a file such as an image or PDF directly in the user's browser instead of downloading it. This method accepts the file path as the first parameter and the header information array as the second parameter:
return response()->file($pathToFile); return response()->file($pathToFile, $headers);
If you want to define a custom response that can be reused in multiple routes and controllers, you can use themacromethod on the
Responsefacade. For example, write the following code in the
ResponseFactoryboot
method of a service provider:<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Response; class ResponseMacroServiceProvider extends ServiceProvider{ /** * 注册应用程序的响应宏 * * @return void */ public function boot() { Response::macro('caps', function ($value) { return Response::make(strtoupper($value)); }); } }
macro
The method accepts a name as the first parameter, and the closure function as The second parameter. The closure of the response macro is executed when the macro name is called in theimplementation class or helper function
response
:
This article was first published inreturn response()->caps('foo');
LearnKu. com
on the website.
- Jump to controller Action