Laravel5.2-http Middleware Study

Source: Internet
Author: User
Tags http redirect

HTTP Middleware

Introduction

HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware this verifies the user of your application is authenticated. If the user is not authenticated, the middleware would redirect the user to the login screen. However, if the user is authenticated, the middleware would allow the request to proceed further into the application.

Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS Middleware might is responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.

There is several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware is located in the app/http/middlewaredirectory.

Defining middleware

To create a new middleware, use the Make:middlewareartisan command:

Creating middleware can be created using tools, and artisan is a great tool to help you create some middleware or other

PHP Artisan Make:middleware Agemiddleware

This command creates a middleware (actually a class) in your App/http/middleware directory, and the file contains some well-written templates, such as here,

Cat app/http/middleware/agemiddleware.php<? phpnamespace app\http\middleware;use Closure;class AgeMiddleware{    /**     * Handle an incoming request.     *     * @param  \illuminate\http\request  $request     * @param  \closure  $next     * @return Mixed     *    /Public Function handle ($request, Closure $next)//support 2 parameters, one is request, and the other is a closure (temporarily unknown)    {        return $ Next ($request); Returns a processed $request    }}//This is just the default example.

This command would place a new agemiddlewareclass within your app/http/middlewaredirectory. In this middleware, we'll only have access to the route if the supplied Ageis greater than 200. Otherwise, we'll redirect the users back to the "home" URI.

This middleware has been modified to allow only requests that support age greater than 200 to enter the route, otherwise redirect to the home page

 
  Input (' age ') < = 200) {//Call the input method, and pass in the parameter age,            return redirect (' home ');        }        Return $next ($request);}    }

As can see, if the given ageis less than or equal to, the middleware would return an HTTP redirect to the client; Otherwise, the request is passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), simply call the $nextcallback with th E $request.

Middleware is a bit like a filter, like a series of filtering layers to constantly filter HTTP requests.

It's envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

Before/aftermiddleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task beforethe request was handled by the application:

A middleware is to look at the middleware itself before or after the request arrives, and this is done before the request.

< Phpnamespace app\http\middleware;use Closure;class beforemiddleware   //Visible sign beforemiddleware{public    function handle ($request, Closure $next)    {        //Perform Action        return $next ($request);}    }

However, this middleware would perform it task after the request was handled by the application:

    

Registering middleware

Global Middleware

If you want a middleware to being run during every HTTP request to your application, simply list of the middleware class in the $middlewareproperty of your app/http/kernel.phpclass.

If middleware is required to operate on every Http request, the simple notation is to write the middleware in the app/http/kernel.php

$middleware attributes, such as

    protected $middleware = [        \illuminate\foundation\http\middleware\checkformaintenancemode::class,    ];

Assigning Middleware to Routes

The middleware assigned to the route needs to create a short name for the middleware in your app/http/kernel.php (as in the following example),

If you would like to assign middleware to specific routes, you should first assign the middleware a Short-hand key in your App/http/kernel.phpfile. By default, the $routeMiddlewareproperty of this class contains entries for the middleware included with Laravel. To add your own, simply append it to the this list and assign it a key of your choosing. For example:

Within app\http\kernel class...protected $routeMiddleware = [    ' auth ' + = \app\http\middleware\authenticate:: class,//Just like this, bind the name middleware    ' Auth.basic ' to \illuminate\auth\middleware\authenticatewithbasicauth::class,    ' Guest ' = \app\http\middleware\redirectifauthenticated::class,    ' throttle ' and \illuminate\routing\ Middleware\throttlerequests::class,];

Once The middleware have been defined in the HTTP kernel, you may use the Middlewarekey in the route options array:

Route::get (' Admin/profile ', [' middleware ' = ' auth ', function () {    //The middleware used in the route can be specified}]);

Use a array to assign multiple middleware to the route:

Route::get ('/', [' middleware ' = [' first ', ' second '], function () {    //Allocate multiple middleware can be used in an array}]);

Instead of using an array, also chain the Middlewaremethod onto the route definition:

Route::get ('/', function () {    

When assigning middleware, your may also pass the fully qualified class name:

Use App\http\middleware\foomiddleware; Route::get (' Admin/profile ', [' middleware ' + foomiddleware::class, function ()}    //Pass a complete middleware class name, plus the use part, Because you are looking for a location}]);

Middleware Groups

Sometimes want to group several middleware under a single key to make them easier to assign to routes. You could do this using the $middlewareGroupsproperty of your HTTP kernel.

Using middleware groups, using $middlewareGroups properties

Out of the-box, Laravel comes with Weband apimiddleware groups that contains common middleware you could want to apply to We b UI and your API routes:

The default laravel is the 5.2 version of the middleware group that provides the Web and API, and he contains the common middleware

/** * The application ' s route middleware groups. * * @var array */protected $middlewareGroups = [//Here is $middlewaregroups    ' web ' =        [\app\http\middleware\ Encryptcookies::class,        \illuminate\cookie\middleware\addqueuedcookiestoresponse::class,        \Illuminate\ Session\middleware\startsession::class,        \illuminate\view\middleware\shareerrorsfromsession::class,        \ App\http\middleware\verifycsrftoken::class,    ],//each defined a number of middleware, such as some cookie,session middleware    ' api ' = [        ' throttle:60,1 ',        ' Auth:api ',    ],];

Middleware groups May is assigned to routes and controller actions using the same syntax as individual middleware. Again, middleware groups simply make it much convenient to assign many middleware to a route at once: using the same command can be like using a single middleware to The middleware group is assigned to the routing or controller,

Route::group ([' middleware ' + = [' web ']], function () {    //here uses $middlewaregroups to compile the middleware group, but can still be invoked using a single middleware. });

Middleware Parameters

Middleware can also receive additional custom parameters. For example, if your application needs to verify so the authenticated user has a given "role" before performing a given Action, you could create a rolemiddlewarethat receives a role name as an additional argument.

Middleware will receive additional parameters, for example, if your application needs to verify that the user has a role before performing the action, you should create a rolemiddleware to receive this additional parameter.

Additional middleware parameters'll be a passed to the middleware after the $nextargument:

Additional middleware parameters are passed to the back of the $next of the middleware

< Phpnamespace app\http\middleware;use Closure;class rolemiddleware{    /**     * Run the request filter.     *     * @param  \illuminate\http\request  $request     * @param  \closure  $next     * @param  String  $role     * @return Mixed */public    function handle ($request, Closure $next, $role)//Added a $ Role parameter    {        if (! $request->user ()->hasrole ($role)) {            //Redirect ...        }        Return $next ($request);}    }

Middleware parameters May is specified when defining the route is separating the middleware name and parameters with a:. Multiple parameters should be delimited by commas:

Route::p ut (' Post/{id} ', [' middleware ' = ' role:editor ', function ($id) {    //separated by colons, name of the middleware: parameters, which can also specify the parameters of the Middleware}]);

Terminable Middleware

Sometimes you need a middleware that handles some of the HTTP responses that have been sent to the browser, such as the session middleware, which consists of laravel writing session data and storing it, after the HTTP response is sent to the browser,

Sometimes a middleware may need to does some work after the HTTP response have already been sent to the browser. For example, the ' session ' middleware included with Laravel writes the session data to storage afterthe response have been Sent to the browser. To accomplish this, define the middleware as "terminable" by adding a terminatemethod to the middleware:

To achieve this, a terminable middleware is required to add a Terminate method

     

The Terminatemethod should receive both the request and the response. Once you has defined a terminable middleware, you should add it to the list of global middlewares in your HTTP kernel.

When the Terminate method of the middleware is called, Laravel will decompose a fresh middleware instance from the service container, and if you use the same middleware instance when the handle and terminate methods are called, will use this container singleton method to register the middleware

When calling the Terminatemethod on your middleware, Laravel would resolve a fresh instance of the middleware from the Serv Ice container. If you would the same middleware instance when the Handleand Terminatemethods is called, register the Middlew is with the container using the container ' s singletonmethod.

Reference:

Https://laravel.com/docs/5.2/middleware

Http://laravelacademy.org/post/2803.html

This article was authored by Peteryuan and licensed under the Attribution-NonCommercial use of 2.5 mainland China. Please contact the author and the author and indicate the source of the article before reprint or citation. The same young»laravel5.2-http middleware study

  • 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.