Laravel Learning Notes-routing (middleware and routing groups)

Source: Internet
Author: User
Tags auth closure documentation json php file

Source: Http://insp.top/learn-laravel-middleware-routegroup

The previous section describes the basic usage of Laravel routing, and now we want to learn more about what is on the route.

This article contains the following subsections, and it is recommended to read the official documentation before reading. Middleware routing Groups

Middleware

In the official document, this part is behind the route, but I want to move it to the front, which is more reasonable.

What is this?

We know that routing is a process that parses requests from clients and distributes them to the appropriate processing logic according to the routing rules. But there is a situation, metaphorically: backstage. The background is not accessible to everyone, we need to do a validation before formal processing logic, such as verifying that the permission is available or whether the requested data is legitimate.

At this point, the middleware is part of the routing process.

The HTTP middleware provides a convenient mechanism to filter HTTP requests into the application, for example, Laravel contains a middleware to verify user authentication by default, and if the user is not authenticated, the middleware directs the user to the login page, however, if the user is authenticated, The middleware will allow this request to move further forward.

The above content from the Chinese version of the Laravel 5 document, which is a good explanation of the role of middleware. In versions prior to Laravel 5, only filters (route filters), as in the current middleware, are an intermediate process between request and processing logic, and are generally used as pre-and post-judgment and validation. Through the middleware we can focus on its own logic in the controller, like a back-end controller, I just need to focus on displaying the user list or article list, to deal with the added articles and so on, and do not need to focus on whether the visitor is a legitimate background administrator, verify the permissions of the work, should be referred to the middleware. The middleware validation will be handled normally, and the non-pass will be redirected or otherwise manipulated.

Laravel has built-in many middleware by default and is turned on by default. You can decide whether to enable these middleware by editing app/http/kernel.php. The middleware I developed is also registered here.

The $middleware array in app/http/kernel.php is the global middleware, that is, any route will be applied to these middleware, such as the CSRF verification middleware inside.

Sometimes we do not need the global middleware, this time you can register a middleware to the app/http/kernel.php file in the $routeMiddleware array, the array's key name is the middleware alias, the key value is the specific middleware class, such as

' Auth ' = ' app\http\middleware\authmiddleware '.

Specifically how to use specific middleware on a one-way, we continue below.

Our $routeMiddleware array in the app/http/kernel.php file registers a separate middleware that can be used to bind to a routing and routing group alone. The route definition can look like this:

Route::get (' Admin/profile ', [' middleware ' = ' auth ', function () {//}]);

When we visit Http://yourdomain/admin/profile, we first go through the global middleware, and then we define the name auth in the app/http/kernel.php $routeMiddleware array. of middleware.

Having said so much about how to define, what should be inside the middleware class. You should know this when you read the documentation (there are some differences between the following code and the documentation):

<?php namespace App\http\middleware; Use Closure;   Use Auth; Class Authmiddleware {/** * Run the request filter. * * @param \illuminate\http\request $request * @param \closure $nex T * @return Mixed */Public function handle ($request, Closure $next) {//If the user was not logged in If (Auth::guest ()) {if ($request->ajax ()) {return response (' unauthorized! ', 401);} else {return redirect ()->guest (' Admin/login ');} } view ()->share (' Loign ', true); Return $next ($request); }   }

The above code is a well-written middleware, the content of the handle method is the actual code of the middleware.

We can see that the 18th to 27th line of code is probably a process of judging whether a user is logged in or not, if the request is Ajax type, the AJAX type request returns a JSON data that says "You don't have permission" (just understand), Redirect to the login interface if it is a standard request.

If in the middleware, through your validation, or the pre-operating logic, remember to pass the code return $next ($request) (28 lines in the example above) the request to the next middleware, if there is no middleware, will be to the processing logic (such as controller, etc.).

The above middleware is a pre-operational middleware, what does it mean. The middleware that is in front of the actual processing logic is a front-facing middleware. Conversely, when an actual processing logic runs out of the middleware, it is a post-middleware.

The post-middleware structure is as follows:

<?php namespace App\http\middleware; Class Aftermiddleware implements middleware {public function handle ($request, Closure $next) {$response = $next ($reque   ST); The specific middleware logic code return $response; } }

We can see that the difference is that there is a $response = $next ($request) and the return value has changed. It's good to understand that the value returned by the $next ($request) is the final response of the entire request after countless specific processing logic, typically a bunch of HTML code (the rendered view) or a JSON, and so on. We can do the final processing of this response in the middleware, and finally return the processed results. Routing Group

This official document has a very detailed description, but it does not seem easy to understand. Let's talk about the applicable scenario.

Routing groups are often applied to a class of routing groups, and the middleware, filters, etc. assigned to this routing group are applied to all routes within the group.

The

Frankly, routing groups are simplifying part of the route definition process. For example, I want to go through address  http://yourdomain/admin/***  access in the background, if I have   users (user), article (article)   two modules, They have access to a middleware that validates permissions, and I need to define routes like this:

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.