Six basic components - HTTP response

Creating a response

   An array of strings &

     All routing and service logic controller after the processing returns a response to the user's browser transmits, Laravel provides several different ways to return the response, the response is to return a basic simple string or from the routing controller, frame will automatically string into a complete HTTP response:

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

     In addition to or from the routing controller returns the string, you can also return an array. Frame will automatically be transformed into an array of JSON response:

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

     Note: You can also return Eloquent know from the set of routing or control it? They will be automatically converted into JSON response.

   Response object

     Usually, we do not simply return the string and an array of routes from the action, in most cases, it will return a complete Illuminate\Http\Response instance or view.

     Returns the complete  Response instance allows you to customize the response status code and an HTTP response headers. Response Examples of inherited from  Symfony\Component\HttpFoundation\Response class, which provides various methods of constructing an HTTP response:

Route::get('home', function () {
    return response('Hello World', 200)->header('Content-Type', 'text/plain');
});

   Add response header

     Most of the response methods are available chained calls, making the process of creating a response examples more readable. For example, you can use the response back to the user before the  header method to add a bunch of headers:

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 specify an array of header information to be added to the response:

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

   Cache Control Middleware

     Laravel a built  cache.headers intermediate that can be used to quickly set up the routing group  Cache-Control header. If concentrated in the instruction statement  etag, Laravel automatically ETag identifier is set in response to the MD5 hash of the contents of:

Route::middleware('cache.headers:public;max_age=2628000;etag')->group(function() {
    Route::get('privacy', function () {
        // ...
    });

    Route::get('terms', function () {
        // ...
    });
});

   Adding Cookies to respond

     You can use the response  cookie easy method for increasing the response Cookies . For example, you can use something like this  cookie method of generating a cookie and easily attach it to the response:

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

   cookie The method also accepts a number of parameters are less frequently used. Typically, these parameters and native PHP setcookie method has the same purpose and meaning:

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

     Alternatively, you can use the  Cookie facade "queue"  Cookie to attach to the application's outgoing responses. queue Method takes an  Cookie instance or create  Cookie the required parameters instance. These cookie before being sent to the browser into the outgoing response:

Cookie::queue(Cookie::make('name', 'value', $minutes));

Cookie::queue('name', 'value', $minutes);

   Cookies & Encryption

     By default, all Cookie Laravel generated are encrypted and signed, and therefore can not be modified or read client. If you want to apply part of the Cookie generated by the program is not encrypted, you can use the  app/Http/Middleware directory  App\Http\Middleware\EncryptCookies middleware  $except attributes:

/ * * 
 * Need not be encrypted cookies name 
 * 
 * @var Array 
 * / 
protected  $ the except = [
     'cookie_name', 
];

Redirect

   Redirection responses are  Illuminate\Http\RedirectResponse instances of classes, and comprises header information the user needs to be redirected to another URL required. Laravel provides several methods for generating  RedirectResponse instances. The simplest method is to use a global auxiliary functions  redirect:

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

   Sometimes you might want to redirect the user to the previous location, such as an invalid form submitted at the time. Then you can use the global helper function  back to do this. Because of this use of session control function, make sure to call  back routing functions using  web middleware middleware groups, or all Session:

:: POST the Route ( 'User / Profile', function () {
     // verification request 
    return Back () -> withInput (); 
});

   Redirect to a named route

     If the call without auxiliary function parameters  redirect , return  Illuminate\Routing\Redirector instance. This example allows you to call  Redirector any method on. Generating, for example, name the route  RedirectResponse, may be used  route methods:

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

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

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

   By filling parameter model Eloquent

     If you want to use the redirects from Eloquent routing model fill "ID" parameter, you can simply transfer model itself. ID will be automatically extracted:

// For the route with the following URI: Profile / {ID} 
return the redirect () -> route ( 'Profile', [ $ User ]);

     If you want to customize the default parameter name this routing parameters, the model instance needs to be rewritten  getRouteKey method:

/ * * 
 * Get Model routing keys 
 * 
 * Mixed @return 
 * / 
public  function getRouteKey () 
{ 
    return  $ the this -> Slug; 
}

Jump to Controller Action

    You may also be generated to the controller action jump. To achieve this purpose, as long as the name of the controller and passed to the action  action method. Remember, do not need to pass all of the namespace controller, Laravel is  RouteServiceProvider automatically set to the namespace basic controller:

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

     If the controller requires the routing parameters, which can be used as  action a method of the second argument:

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

   Jump to the external domain name

     Sometimes you need to jump to a domain outside of the application. Call the  away ways to achieve this purpose, it will create a URL without any additional coding, validity checking and inspection  RedirectResponse examples:

 return redirect()->away('https://www.google.com');

   Jump values ​​with transmission Session

     Jump to new URL of simultaneous transmission of data to the session is very common. And usually transmit a message to do so after the session in the successful implementation of an action. For convenience, you can create an  RedirectResponse instance of the data will be transmitted to the session and called the chain method:

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

     After the jump the user may be displayed in the data transfer session. Such as the use Blade syntax:

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

Other types of responses

     response Examples of assistants may be used to generate other types of response. When also called with no arguments  response when assistant, returns  Illuminate\Contracts\Routing\ResponseFactory contract an implementation. The contract number is provided a method for generating a response:

   View response

     If you need to view the contents of a response while returning, in response to the control and status information header, it is necessary to call  view the method:

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

     If no HTTP status code is transmitted and custom-defined header information, you may also be used global  view helper functions.

   JSON response

   json Automatically  Content-Type header information set  application/json, use of PHP  json_encode function given array to a JSON:

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

     If you want to create a JSONP response, can be combined  withCallback method  json method:

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

     Direct use or  jsonp method:

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

file download

   download The method may be used to generate a force in response to the user's browser to download a predetermined file path. download Methods filename as its second argument, it will download the file as the user name. Finally, you can pass an array of HTTP header information as its third parameter:

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

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

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

     Note: for managing files downloaded Symfony HttpFoundation asked to download the file has an ASCII file name.

     For example, we can download the picture by the following code:

Route::get('download/response', function() {
    return response()->download(storage_path('app/photo/test.jpg'), '测试图片.jpg');
});

   Stream download

     Sometimes, you may want to convert the given string response operations for downloading response, without the need to be written to disk. You can now use  streamDownload the method. This method accepts a callback, file name and an optional array header information as a parameter:

return response()->streamDownload(function () {
    echo GitHub::api('repo')
                ->contents()
                ->readme('laravel', 'laravel')['contents'];
}, 'laravel-readme.md');

   Response to

   file Method for direct display a picture or PDF file like the user's browser instead of downloading. This method takes the file path as the first parameter, as the second header information array parameters:

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

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

   Macro response

     If you want to define the response may be multiplexed in a plurality of routing controllers and custom, may be used  Response on the facade  macro method. For example, a service provider's  boot method write the following code:

<?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 argument, the closure as a function of the second parameter. In response to the macro closure  ResponseFactory class or auxiliary function  response when calling the macro name to be executed:

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

     Visit in the browser / macro/responseoutput into the next:

foo

 

 

 

Guess you like

Origin www.cnblogs.com/mzhaox/p/11264052.html