Laravel 5.5 How do I create a response? Introduction to creating a response (code)

Source: Internet
Author: User
How does the Laravel 5.5 create a response? Probably a lot of people are not very clear, then, next I will introduce you about Laravel 5.5 to create an HTTP response and explain the other types of response.

Create response

Strings & Arrays

All routes and controllers return a response that is sent to the user's browser after the business logic is processed, and Laravel provides a number of different ways to return the response, and the most basic response is to return a simple string from the route or controller, and the framework automatically translates the string into a full HTTP response.

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

In addition to returning a string from a route or controller, you can also return an array. The framework automatically transforms the array into a JSON response.

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

Note: You can also return the eloquent collection from a route or controller, which is also automatically converted to a JSON response.

Response Object

In general, we do not simply return a string or array from a simple route, and in most cases a full illuminate\http\response instance or view is returned.

Returning a full Response instance allows you to customize the HTTP status code and header information for the response. The Response instance inherits from the Symfony\component\httpfoundation\response base class, which provides a series of methods for creating HTTP responses.

Route::get ('/', function () {    return response (' Hello world ', $)        ->header (' Content-type ', ' Text/plain ');});

Add a response header

Most response methods can be called in the form of a chain of methods, so that the response can be streamed (Stream interface mode). For example, you can use the header method to add a series of response headers before sending a response to a user.

return response ($content)    ->header (' Content-type ', $type)    ->header (' X-header-one ', ' Header Value ')    ->header (' x-header-two ', ' header Value ');

Or you can use the Withheaders method to specify an array of header information to add to the response.

return response ($content)    ->withheaders ([        ' content-type ' = $type,        ' x-header-one ' + ' Header Value ',        ' x-header-two ' = ' Header value ',    ]);

Add a Cookie to a response

Cookies can be easily added to a response using the cookie method on the response instance. For example, you can use a cookie method to generate a cookie and add it to the response instance.

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

The cookie method can also receive additional optional parameters that are less frequently used, and in general, these parameters are similar to the Setcookie methods provided by PHP native.

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

In addition, cookies can be added to a response in a "queue" form using a cookie façade. The queue method receives a cookie instance or a parameter that is necessary to create a cookie, which is added to the response before the response is sent to the browser.

Route::get (' Cookie/response ', function () {    cookie::queue (cookie::make (' site ', ' www.baidu.com ', 1));    Cookie::queue (' author ', ' admin ', 1);        Return response (' Hello Laravel ', $)        ->header (' Content-type ', ' Text/plain ');});

You can see these two new cookies by accessing Http://www.adm.devp/cookie/response in the browser.

Cookie encryption

By default, the cookies generated by the Laravel framework are encrypted and signed to avoid tampering with the client. If you want to allow a specific subset of cookies to be unencrypted at build time, you can exclude these by using the $except properties provided by the middleware app\http\middleware\encryptcookies in the App/http/middleware directory. Cookies.

/** * Does not require an encrypted cookie name * * @var array */protected $except = [    ' Cookie_name ',];

redirect

The redirect response is an instance of the Illuminate\http\redirectresponse class, contains the necessary header information to redirect the user to another URL, and there are many ways to generate the Redirectresponse instance, the simplest way is to use the global helper function 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 validation does not pass, you can use the helper function back to return to the previous URL (since the function uses the Session, before using this method to ensure that the relevant route is in the Web Middleware group or applied Session middleware).

Route::p ost (' User/profile ', function () {    //Validate request ...    return back ()->withinput ();});

Redirect to named Route

If you call the redirect method without parameters, you return a Illuminate\routing\redirector instance, and then you can use all the methods on the redirector instance.

For example, to generate a redirectresponse-to-named route, you can use the route method.

Return Redirect ()->route (' login ');

If there are parameters in the route, they can be passed to the route method as a second parameter:

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

Populating route parameters with the eloquent model

If you are redirecting to a route with an ID parameter (eloquent model binding), you can pass the model itself, and the ID will be parsed automatically.

Return Redirect ()->route (' profile ', [$user]);

If you want to customize the default parameter name in this routing parameter (the default is ID), you need to override the Getroutekey method on the model instance.

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

Redirect to Controller method

You can also generate a method to redirect to the controller, simply passing the controller and method name to the action method. Remember, you do not need to specify the full namespace of the controller, because Laravel's routeserviceprovider will automatically set the default controller namespace.

Return Redirect ()->action (' Homecontroller@index ');

As with the route method, if the controller route requires parameters, you can pass the parameter as the second parameter to the action method.

Return Redirect ()->action (' Usercontroller@profile ', [' ID ' =>1]);

Redirect with one-time Session data

Redirecting to a new URL and storing the data in a one-time session is usually done simultaneously, for convenience, you can create a Redirectresponse instance and then store the data in the session on the same method chain, in the action It is particularly convenient to store state information afterwards.

Route::p ost (' User/profile ', function () {    //update user Properties    ... Return redirect (' dashboard ')->with (' status ', ' Profile updated! ');});

After the user redirects to the new page, you can remove and display these one-time messages from the Session, using the Blade syntax to implement the following:

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

Note: This one-time representation after the first data is removed from the Session, the data will be destroyed and no longer exist.

Other response types

We talked about the Response and redirectresponse two response types, and we can easily generate other types of response instances through the helper function Response, and return illuminate\ when no arguments are called Response An implementation of the Contracts\routing\responsefactory contract, which provides some useful ways to generate various responses, such as view responses, JSON responses, file downloads, stream responses, and so on.

View response

You can use the view method if you need to control the response status and response headers, and you also need to return a view as the response content.

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

Of course, if you don't need to pass the custom HTTP status code and header information, simply use the Global helper function view.

Route::get (' View/response ', function () {   return view (' Hello ');});

Note: The view file for the view response must exist and the view file is in the Resources/views directory.

JSON response

The JSON method automatically sets the Content-type header to Application/json and uses the PHP function Json_encode method to convert the given array into JSON-formatted data.

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

If you want to create a JSONP response, you can call the Withcallback method after the JSON method.

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

Or use the Jsonp method directly.

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

File download

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

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

Note: The Symfony httpfoundation class that manages file downloads requires that the downloaded file has an ASCII file name, which means the downloaded filename cannot be in Chinese.

Route::get (' Download/response ', function () {    return response ()->download (Storage_path (' app/photo/test.jpg ') ), ' test picture. jpg ');

File response

The file method can be used to display files, samples, or PDFs directly in the user's browser, without the need for a download, which receives the file path as the first parameter, and an array of header information as the second parameter.

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

Response macro

If you want to define a custom response that can be multiplexed across multiple routes and controllers, you can use the macro method on the Response façade.

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

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

The macro method receives the response name as the first argument, and the closure function as the second argument, the closure of the response macro is executed when the macro name is called in the Responsefactory implementation class or in the helper function response.

Route::get (' Macro/response ', function () {    return response ()->caps (' Test ');});

Access Http://www.adm.devp/macro/response in the browser, output in:

TEST
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.