Laravel basic usage, Cookie generation, return view, JSON/JSONP, file download and redirection

Source: Internet
Author: User
Tags json

1. Response
1.1 Basic response

The most basic HTTP Response only needs to return a simple string in the routing closure or controller action, but most of the responses in the specific business logic return the Response instance or view in the controller action. Response is an instance of the Illuminate \ Http \ Response class inherited from Symfony \ Component \ HttpFoundation \ Response. We can use a series of methods on this instance to create an HTTP Response:

Use Illuminate \ Http \ Response;

Route: get ('testresponse', function (){
$ Content = 'Hello LaravelAcademy! ';
$ Status = 200;
$ Value = 'text/html; charset = utf-8 ';
Return (new Response ($ content, $ status)-> header ('content-type', $ value );
});
Access in the browser, F12 view the response header information (Chrome browser ):

Basic response

If we try to modify $ status = 500, the header information is as follows:

Basic response 2

For ease of use, we can also use the global help function response to replace the Response object generation instance:

Route: get ('testresponse', function (){
$ Content = 'Hello LaravelAcademy! ';
$ Status = 500;
$ Value = 'text/html; charset = utf-8 ';
Return response ($ content, $ status)-> header ('content-type', $ value );
});
The effect is the same. In the future, this method will be used by default and no Response object instance will be generated.

In addition, ResponseTrait is also used in the Illuminate \ Http \ Response class. The header method is provided by the trait. Besides the header, the trait also provides the withCookie, content, and status methods. The header method is used to set the Response header information. The withCookie method is used to add a cookie. Both methods return the Response object that calls it, therefore, both methods support method chains (that is, the header or withCookie method is called multiple times), while the content and status methods are used to return the response entity content and response status code of the current response.

1.2 Add Cookie

As mentioned above, we use the withCookie method to add a cookie to the response. Because header and withCookie support method chain, we can use the following method as follows:

Route: get ('testresponsecooker', function (){
$ Content = 'Hello LaravelAcademy! ';
$ Status = 200;
$ Value = 'text/html; charset = utf-8 ';
Return response ($ content, $ status)-> header ('content-type', $ value)
-> WithCookie ('Site', 'laravelemy Emy. org ');
});
Access in the browser, F12 view Cookie information:

Generate Cookie

We can also use the cookie's validity period, scope, and other information:

Route: get ('testresponsecooker', function (){
$ Content = 'Hello LaravelAcademy! ';
$ Status = 200;
$ Value = 'text/html; charset = utf-8 ';
// Set the cookie to be valid for 30 minutes. The path is the application root directory and the scope name is laravel. app.
Return response ($ content, $ status)-> header ('content-type', $ value)
-> WithCookie ('Site', 'laravelemy Emy. org ', 30,'/', 'laravel. App ');
});
Note: The withCookie method actually calls the global help function cookie to generate a cookie, and then puts the cookie in the response header.
Visit again in the browser, and F12 will view the cookie information as follows:

Generate cookie

The validity period, domain name, and other related information are provided.

In addition, we also note that the cookie is encrypted, which we have mentioned earlier. This is for the sake of security. If you want to cancel encryption, in app/Http/Middleware/EncryptCookies. in the php file, add the corresponding cookie name to the EncryptCookies class attribute $ cookie T:

<? Php

Namespace App \ Http \ Middleware;

Use Illuminate \ Cookie \ Middleware \ EncryptCookies as BaseEncrypter;

Class EncryptCookies extends BaseEncrypter
{
/**
* Unencrypted cookie name
     *
* @ Var array
*/
Protected $ Partition T = [
'Site'
];
}
Access the http://laravel.app again in the browser: 8000/testResponseCookie, F12 view Cookie information as follows:

Unencrypted cookie

Of course, we do not recommend this for the sake of security.

2. ResponseFactory
If the response function does not pass in the parameter, it will return the implementation of the Illuminate \ Contracts \ Routing \ ResponseFactory contract -- Illuminate \ Routing \ ResponseFactory, which provides multiple methods to generate richer response types, for example, view response, JSON response, and file download.

2.1 View response

You can use the view method to return a view as the response content:

Route: get ('testresponseview', function (){
$ Value = 'text/html; charset = utf-8 ';
Return response ()-> view ('hello', ['message' => 'Hello laravelemy Emy '])
-> Header ('content-type', $ value );
});
Corresponding to this, we need to create a new view file hello. blade. php under resources/views. Its content is as follows:

{$ Message }}
Next we access the http://laravel.app: 8000/testResponseView in the browser, the page output:

Hello LaravelAcademy
You can also simplify it. If you do not need to customize the HTTP response header, you can also directly use the global help function view:

Route: get ('testresponseview', function (){
$ Value = 'text/html; charset = utf-8 ';
Return view ('hello', ['message' => 'Hello laravelemy Emy ']);
});
The effect is the same as above.

2.2 return JSON/JSONP

You can also use the json method to return data in json format:

Route: get ('testresponsejson', function (){
Return response ()-> json (['name' => 'laravelemy Emy ', 'passwd' => 'laravelemy Emy. org']);
});
Access in the browser and F12 will view the response header information:

Generate json response

According to the output information, the json method automatically sets the Content-Type to application/json, and calls the PHP built-in function json_encode to convert the array to a json string.

If the response is a JSONP response, it is also very simple. You only need to call setCallback after json:

Route: get ('testresponsejson', function (){
Return response ()-> json (['name' => 'laravelemy Emy ', 'passwd' => 'laravelemy Emy. org'])
-> SetCallback (request ()-> input ('callback '));
});
2.3 file download

You can use the download method to generate a response for downloading the file in the specified path. Here we download the file uploaded in the previous section:

Route: get ('testresponsedownload', function (){
Return response ()-> download (
Realpath (base_path ('public/images'). '/laravel-5-1.jpg ',
'Laravel .jpg'
);
});
Access yun_qi_img/testrew.sedownloadin the browser. The page will download the laravel-5-1.jpg file and save it as laravel.jpg.

3. RedirectResponse
The redirected response is an instance of the Illuminate \ Http \ RedirectResponse class. We usually use the global help function redirect to generate a RedirectResponse instance. Similar to response, if the redirect function receives a parameter, it calls the to method of the Illuminate \ Routing \ Redirector class. If no parameter is called, the Redirector object instance is returned.

3.1 Basic redirection

Route: get ('dashboard', function (){
Return redirect ('Home/dashboard ');
});
If you want to redirect to the previous position, use the back method:

Route: post ('user/profile ', function (){
// Verify the request...
Return back ()-> withInput ();
});
3.2 redirect to named route

Use the route method to redirect to the named route:

Route: get ('/hello/laravelemy Emy', ['as' => 'army', function (){
Return 'Hello laravelemy Emy ';
}]);

Route: get ('testresponseredirect', function (){
Return redirect ()-> route ('emy Emy ');
});
Access the http://laravel.app: 8000/testrew.seredirect in a browser and the page jumps to the http://laravel.app: 8000/hello/laravelacademy and outputs:

Hello LaravelAcademy
If the named route has parameters, you can input the parameters in route:

Route: get ('/hello/laravelacademy/{id}', ['as' => 'adsory', function ($ id ){
Return 'Hello laravelemy Emy '. $ id;
}]);

Route: get ('testresponseredirect', function (){
Return redirect ()-> route ('army', 100 );
});
Access the http://laravel.app: 8000/testrew.seredirect in a browser and the page jumps to the http://laravel.app: 8000/hello/laravelacademy/100 and outputs:

Hello laravelacademia 100
3.3 redirect to controller action

Use the action method to redirect to the controller action:

Route: resource ('post', 'postcontroller ');

Route: get ('testresponseredirect', function (){
Return redirect ()-> action ('postcontroller @ index ');
});
Access http://laravel.app: 8000/testrew.seredirect in a browser, the page jumps to http://laravel.app: 8000/post and outputs the corresponding content.

Of course, you can also pass parameters to the action method:

Route: get ('testresponseredirect', function (){
Return redirect ()-> action ('postcontroller @ Show', [1]);
});
3.4 redirection with one-time Session data

The with method can carry the one-time session data to the redirect request page (the session data is destroyed immediately after the one-time session data is used ):

Route: post ('user/profile ', function (){
// Update user attributes...
Return redirect ('dashboard')-> with ('status', 'Profile updated! ');
});
This feature is usually useful when an error message is returned when form verification fails to be submitted.

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.