Laravel basic tutorial -- response-php Tutorial

Source: Internet
Author: User
Laravel basic tutorial-basic response to HTTP responses

All the routes and controllers should return a response and send it back to the user's browser. laravel provides multiple methods to return the response. The most basic response is to simply return a string in a route or controller:

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

The returned string is automatically converted to an HTTP response by laravel.

Response object

In most cases, the routing or controller action should return the Illuminate \ Http \ Response instance or view. The Response instance allows you to conveniently customize the Response header and Response status. A Response instance inherits from the Symfony \ Component \ HttpFoundation \ Response class, which provides multiple methods to generate an HTTP Response:

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

Laravel also provides convenient response global help functions:

Route::get('home', function () {  return response($content, $status)            ->header('Content-Type', $value);});

You can view the API documentation and Symfony API documentation for the methods of using Response instances.

Additional response header

Most methods of Response instances allow chained calls. you can use chained calls to build a Response fluently. For example, you can use the header method to add multiple response headers before they are sent to the user client:

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

Alternatively, you can use the withHeaders method to add request headers to the response through the specified array:

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

The cookie of the Response instance can simply append the cookie information to the Response. For example, you can use the cookie method to generate a cookie and append it to the response:

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

The cookie method allows you to add additional parameters to further customize your cookie attributes:

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

By default, all cookies in laravel are encrypted by visa, so client users cannot modify or interpret them. if you want to disable the default encryption when generating some cookies, you need to append them to the $ encryption T attribute of the App \ Http \ Middleware \ EncreyptCookies Middleware:

protected $except = [  'cookie_name'];
Other response types

The help method response can also be used to conveniently generate other types of response instances. if you use the response help method without passing any parameters, then it returns an instance that implements Illuminate \ Contracts \ Routing \ ResponseFactory contract. This contract provides multiple useful methods to generate responses.

View response

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

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

Of course, if you do not need to customize the response status or response header, you can directly use the global help method view.

JSON response

The json method automatically sets the Content-Type of the response header to application/json, and converts the provided array to JSON using the json_encode method:

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

If you want to generate a jsonp response, you can use the json method and append the setCallback method:

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

The download method can force the client browser to download the response of the specified path file. The download method also allows the second parameter to be passed as the file name for the browser to download. you can also pass the http response header array as the third parameter:

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

Note: the file to be downloaded for Symfony HttpFoundation has an ASCII file name.

File response

The file method allows you to directly display an image or pdf file in a browser instead of directly downloading it. This method takes the path of the received file as the first parameter, or the array of the HTTP response header as the second parameter:

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

A redirected response is an instance of the Illuminate \ Http \ RedirectResponse class. it contains all the response header information required to redirect to a specified URI. Laravel provides multiple methods to generate a redirection instance. The simplest way is to use the global help Method redirect:

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

Sometimes you need to redirect the user to the address of the last request, you can use the global help method back. Because the session is used here, you must ensure that your route uses the session middleware. the default laravel routes are all wrapped in the web routing group, the web middleware group already contains session middleware:

Route::post('user/profile', function () {  // Validate the request...  return  back()->withInput();});
Redirect to named route

When you use the redirect method without passing any parameters, laravel returns an instance of Illuminated \ Routing \ Redirector, which allows you to use some methods to process redirection information, for example, to generate a redirection to a named route, you can use the route method:

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

If the named route also contains parameters, you can pass the second parameter to the route method:

return redirect()->route('profile', ['id' => 1]);

If you want to redirect a route using the id of the Eloquent model as the route for parameter identification, you can directly pass the user instance in the route method, which will be automatically parsed to the id:

return redirect()->route('profile', [$user]);
Redirect to controller behavior

You can also generate redirection information to a behavior of the controller. you can simply pass the controller name and the controller action through the action method to do this. note that you do not need to specify all the namespaces of the controller, because laravel's RouteServiceProvider has automatically set the default namespace:

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

Of course, if your controller behavior also receives other parameters, you can also pass the second parameter in the action method:

return redirect()->action('UserController@profile', ['id' => 1]);
Redirect and Flash session

You can use the chain call of the RedirectResponse instance to flash the seession data while generating the redirection information. This is especially useful when the message status is stored after the execution:

Route::post('user/profile', function () {  // Update the user's profile...  return redirect('dashboard')->with('status', 'profile updated'); });

Of course, when a user redirects to a new page, you can access the Flash session information. for example, in the blade template, you can use the following:

@if (session('status'))   

{{ session('status')}}

@endif
Response macro

If you want to customize a reusable Response, you can use the macro method of Response facade or provide an implementation of Illuminate \ Contracts \ Routing \ ResponseFactory:

    

The macro method receives an alias as the first parameter and a closure as the second parameter. The closure is executed when you access the macro alias of the dynamic attribute of the instance implemented by ResponseFactory, or through the global help method response:

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

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.