Laravel Learning Notes-routing (middleware and routing groups)

Source: Internet
Author: User
This article contains the following sections, which are recommended to read about the official documentation section 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 time, a part of the routing process?? middleware is on the pitch.

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 Laravel5 document, which is a good explanation of the role of middleware. In previous versions of Laravel5, only filters (route filters), as in the present middleware, are an intermediate process between requests 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 are in App/http/kernel.php's $ The middleware named Auth is defined in the Routemiddleware array.

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):

 
  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:

   

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.

In plain parlance, routing groups are a simplification of the route definition process. For example, in the background I would like to access through the address http://yourdomain/admin/***, if I have users (user), the article (article) two modules, their access to go through a verification permission of the middleware, I need to define the route:

Route::get (' Admin/user ', [' middleware ' = ' authority ', function () {    //Blablabla ...}]); Route::get (' admin/article ', [' middleware ' = ' authority ', function () {    //Blablabla ...}]);

Now there are only two routes, I write more than a few admin,middleware, but the system is huge, each to write the corresponding middleware, error prone, difficult to manage. At this point, you should use a routing group:

Route::group ([' prefix ' = ' admin ', ' middleware ' = ' authority '], function () {    route::get (' User ', function () {        //Blablabla ...    });    Route::get (' article ', function () {        //Blablabla ...    });});

At the same time, using routing groups, it is very easy to define sub-domains:

Route::group ([' domain ' = ' bbs.yourdomain.com '], function () {    route::get (' topic ', function () {        // Blablabla ...    });    Route::get (' node ', function () {        ///Blablabla ...    });});

Subdomains can also have wildcards for a more flexible structure. For example, I want every user of my site to have their own level two domain name, similar to this: usera.yourdomain.com,userb.yourdomain.com. This is the time to write:

Route::group ([' domain ' = ' {username}.myapp.com '], function () {    route::get (' Profile/{type} ', function ($ Username, $type)    {        //    });});

You can obtain a wildcard match value on a domain name by using the parameter.

In addition to these, routing group brings the convenience is quite rich, here basically put the meaning of the existence of the routing group is finished, other about the routing group can move to the official document understanding.

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