Laravel5.2-httpmiddleware learning

Source: Internet
Author: User
Tags http redirect
Laravel5.2-httpmiddleware learn HTTP Middleware Introduction

HTTP middleware provide a convenient mechanic for filtering HTTP requests entering your application. for example, Laravel has Des a middleware that verifies the user of your application is authenticated. if the user is not authenticated, the middleware will redirect the user to the login screen. however, if the user is authenticated, the middleware will 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 be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.

There are several middleware encoded in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the app/Http/logs.

Defining Middleware

To create a new middleware, use the make: middlewareArtisan command:

You can use tools to create middleware. artisan is a good tool that helps you create middleware or other products,

php artisan make:middleware AgeMiddleware

This command will create a Middleware (actually a class) in your app/Http/Middleware directory, and the file contains some written templates. for example, 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) // Two parameters are supported. one is request and the other is a closure (temporarily unknown) {return $ next ($ request ); // return a processed $ request} // This is the default example.

This command will place a new AgeMiddlewareclass within your app/Http/Middlewaredirectory. in this middleware, we will only allow access to the route if the supplied ageis greater than 200. otherwise, we will redirect the users back to the "home" URI.

This middleware was modified to allow only requests with age greater than 200 to enter the route. Otherwise, it is redirected to the home page.

 Input ('age') <= 200) {// call the input method and input the parameter age, return redirect ('Home ');} return $ next ($ request );}}

As you can see, if the given ageis less than or equal to 200, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. to pass the request deeper into the application (allowing the middleware to "pass"), simply call the $ nextcallback with the $ request.

The middleware is a bit like a filter, as if a series of filtering layers are constantly filtering http requests.

It's best to 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 wowould perform some taskBeforeThe request is handled by the application:

A middleware depends on the middleware itself before or after the request arrives. the following code is executed before the request arrives.

<? Phpnamespace App \ Http \ Middleware; use Closure; class BeforeMiddleware // The obvious flag BeforeMiddleware {public function handle ($ request, Closure $ next) {// Perform action return $ next ($ request );}}

However, this middleware wowould perform its taskAfterThe request is handled by the application:

 Registering Middleware Global Middleware

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

If you need middleware to operate on each http request, you can simply write the middleware in the app/Http/Kernel. php

$ Middleware attributes, such

    protected $middleware = [        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,    ];
Assigning Middleware To Routes

The middleware assigned to the route must create a short name for the middleware in your app/Http/Kernel. php (for example, below,

If you wowould like to assign middleware to specific routes, you shoshould 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 has Ded with Laravel. to add your own, simply append it to 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, // It seems like this: bind the name to the Middleware 'auth. basic '=> \ Illuminate \ Auth \ Middleware \ AuthenticateWithBasicAuth: class, 'guest' => \ App \ Http \ Middleware \ RedirectIfAuthenticated: class, 'throttle' => \ Illuminate \ Routing \ Middleware \ ThrottleRequests: class,];

Once the middleware has been defined in the HTTP kernel, you may use the middlewarekey in the route options array:

Route: get ('admin/profile ', ['middleware' => 'auth', function () {// you can specify the middleware used in the routing}]);

Use an array to assign multiple middleware to the route:

Route: get ('/', ['middleware Ware '=> ['first', 'second'], function () {// allocate Multiple middleware arrays}]);

Instead of using an array, you may also chain the middlewaremethod onto the route definition:

Route: get ('/', function () {// This is written in chained mode and defined using the middleware method})-> middleware (['first ', 'second']);

When assigning middleware, you 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. you also need to add the use part because you want to find the location}]);
Middleware Groups

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

Use the middleware group and the $ middlewareGroups attribute

Out of the box, Laravel comes with weband apimiddleware groups that contains common middleware you may want to apply to web UI and your API routes:

By default, laravel provides a web and api middleware group in Version 5.2, which includes general 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 \ assumerrorsfromsession: class, \ App \ Http \ Middleware \ VerifyCsrfToken: class,], // Each defines some Middleware, such as some cookies and session Middleware 'api' => ['throttle: 60, 1 ', 'auth: api',],];

Middleware groups may be assigned to routes and controller actions using the same syntax as inpidual middleware. again, middleware groups simply make it more convenient to assign when middleware to a route at once: use the same command to distribute the middleware group to a route or controller like a single middleware,

Route: group (['ddleware '=> ['web'], function () {// $ middlewareGroups is used to compile the middleware group, but it can still be called using a single middleware .});
Middleware Parameters

Middleware can also receive additional custom parameters. for example, if your application needs to verify that the authenticated user has a given "role" before creating a given action, you cocould create a RoleMiddlewarethat named es a role name as an additional argument.

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

Additional middleware parameters will be passed to the middleware after the $ nextargument:

The extra middleware parameters will be passed to the end of $ 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 be specified when defining the route by separating the middleware name and parameters with a:. Multiple parameters shocould be delimited by commas:

Route: put ('post/{id} ', ['middleware Ware' => 'role: editor', function ($ id) {// use a colon to separate, middleware name: Parameter. you can also specify the middleware parameter}]);
Terminable Middleware

Sometimes a middleware is required to process the events that have sent http responses to the browser. for example, session Middleware includes laravel to write and store session data. after an http response is sent to the browser,

Sometimes a middleware may need to do some work after the HTTP response has already been sent to the browser. for example, the "session" middleware failed with Laravel writes the session data to storage afterthe response has been sent to the browser. to accomplish this, define the middleware as "terminable" by adding a terminatemethod to the middleware:

To achieve this, you must add a terminable middleware and a terminate method.

     

The terminatemethod shold receive both the request and the response. Once you have defined a terminable middleware, you shocould add it to the list of global middlewares in your HTTP kernel.

When the terminate method of the middleware is called, laravel will break down a fresh middleware instance from the service container. if the handle and terminate methods are called, you will use the same middleware instance, use the singleton method of the container to register the middleware.

When calling the terminatemethod on your middleware, Laravel will resolve a fresh instance of the middleware from the service container. if you wowould like to use the same middleware instance when the handleand terminatemethods are called, register the middleware 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 created by Peter yuan and is licensed on the Chinese mainland using the signature-non-commercial use 2.5. You need to contact the author before reprinting and referencing, and sign the author and indicate the source of the article. Teenagers like God» laravel5.2-http middleware learning

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.