Laravel5.1 Learning Note 6 responses

Source: Internet
Author: User

    • Basic response
      • Additional header information to the response
      • Attach cookie to Response
    • Other responses
      • View View Response
      • JSON response
      • File download
    • redirect
      • Redirect to named Route
      • Redirect to Controller action
      • Flash session data redirection included
    • Response macro

#基本响应 return a string from a route

The most basic response is to return a string from the Laravel route:

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

Create a custom response

However, for most routes and the actions performed by the controller, you need to return to the full Illuminate\Http\Response instance or a view. When you return a full Response instance, you can customize the HTTP status code of the response and the response header. The Response instance inherits the Symfony\Component\HttpFoundation\Response class, which provides many ways to establish an HTTP response.

 Use Illuminate\http\response;

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


For the sake of convenience, you can use the helper method response :

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

tip: Response A complete list of methods can be referenced in the API documentation as well as the Symfony API documentation.

#附加头信息到响应

Remember that most response methods are chained and are used to create a smooth response. As follows:

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

#附加Cookie到响应 (this saves a lot of nonsense, directly read the code to understand, do not understand the ghost of the document so much nonsense)
return response ($content)->header (' Content-type ', $type)
->withcookie (' name ''value ');

The Withcookie method accepts more optional arguments, allowing you to customize the properties of the cookie

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

By default, all cookies are laravel encrypted and signed so that they cannot be changed by the customer, and if you do not want to encrypt certain cookies, you can use App\Http\Middleware\EncryptCookies the $except properties of the middleware

/**
* The names of the cookies that should is not being encrypted.
*
* @var Array
*/
protected $except = [
' Cookie_name ',
];

#其他响应类型

responseyou can easily produce other types of response instances using the helper method. When you invoke the helper method response without any arguments, the contract implementation is returned Illuminate\Contracts\Routing\ResponseFactory . This contract provides some useful ways to generate a response.

View response

If you need to control the response status and response header, but also need to return a view as the response content, you can use the View method

return response ()->view (' Hello ', $data)->header (' Content-type ', $type);
If you do not need to transfer custom HTTP status, or customize header information, you can use the Global View helper method to establish a JSON response

jsonThe Json_encode method automatically configures the response header to Content-Type application/json, convert a given array array to JSON at the same time, using the PHP method

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

Establish JSONP response
return response ()->json ([' name 'Abigail' state'CA '])
->setcallback ($request->input (' callback '));

Create a response to a file download

The first parameter is a given download directory, the second is the saved file name, and the third is the HTTP header information

return response ()->download ($pathToFile);

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

return response ()->download ($pathToFile)->deletefileaftersend (true);

Note: Symfony Httpfoundation, which manages file downloads, requires the file being downloaded to has an ASCII file name.

#重定向

The redirect response is typically an instance of the class Illuminate\Http\RedirectResponse and contains the response headers that the user needs to redirect to another URL. There are many ways to produce a redirected redirectresponse instance, the simplest way is to use the Global Redirect helper method

Route::get (' dashboard 'function () {
return Redirect (' Home/dashboard ');
});
Sometimes you want to redirect the user to its previous location, such as a form submission failure, and you can use the Global back helper method
Route::p ost (' user/profile 'function () {
Validate the request ...

return back ()->withinput ();
});

Return redirect

There are several ways to produce RedirectResponse an instance, the simplest way is through an auxiliary method redirect . When testing, it is not uncommon to establish a test that simulates a redirect response, so it is often possible to use an auxiliary method:

return Redirect (' User/login ');
Returns redirection based on the route name

When you call the helper method redirect without any arguments, the instance is returned Illuminate\Routing\Redirector , and you can call any method on the instance. For example, to generate a RedirectResponse name to a route, you can use the route method:

return redirect ()->route (' login ');
If your route has parameters, you can pass it as a second argument to the route method
For a route with the following Uri:profile/{id}

return redirect ()->route (' profile ', [1]);
If you are redirecting to a route whose ID parameter is contained in a eloquent model, you can pass the model itself, whose ID is automatically extracted.
return redirect ()->route (' profile ', [$user]);


Returns redirection based on the controller action

Since the instances can be generated and RedirectResponse redirected to the route name, the same can be redirected to the controller action:

return redirect()->action(‘App\Http\Controllers\[email protected]‘);

Tip: If you have URL::setRootControllerNamespace registered the namespace of the root controller, you do not need to action() specify the full namespace for the controller within the method. action()the controller within the method specifies the full namespace.

action()The controller within the method specifies the full namespace.

Returns the redirection based on the controller action, and assigns the parameter to the value
return redirect ()->action (' [email protected] ', [1]);

Returns the redirection based on the controller action and assigns a value to a specific name parameter
return redirect ()->action (' app\http\controllers\[email protected] ', [' user ' = + 1]) ;

Return redirect Plus flash data

Typically redirects to a new URL will store the data in a one-time Session. So for convenience, you can create an instance of the method connection RedirectResponse and store the data in a one-time Session:

Route::p ost (' user/profile 'function () {
Update the user S profile ...

return Redirect ('dashboard ')->with (' status 'profileupdated! ');
});

 

Laravel5.1 Learning Note 6 responses

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.