Laravel study Notes-routing (middleware and routing group) This article contains the following sections. before reading this article, we recommend that you read the relevant sections of the official documentation.
Middleware
Route Group
Middleware
In the official document, this part is behind the route, but it is more reasonable to move it to the front.
What is this?
As we know, routing is a process that analyzes the request from the client and distributes the requests to the corresponding processing logic according to the routing rules. But there is a situation, for example, the background. Not everyone can access the background. before the formal processing logic, we need to perform a verification, such as verifying whether the data with permissions or requests is legal.
What is part of the routing process ??MiddlewareIt's playing.
HTTP middleware provides a convenient mechanism to filter HTTP requests entering the application. for example, Laravel contains a middleware by default to verify user authentication. if the user has not been authenticated, middleware directs the user to the logon page. However, if the user passes authentication, middleware will allow the request to proceed further.
The above content comes from the Chinese version of laravel5 documentation, which demonstrates the role of middleware. In earlier versions of laravel5, only filters (routing filters) are available. The purpose is the same as that of the current middleware, which is an intermediate process between the request and the processing logic, it is generally used for pre-and post-judgment and verification. Through middleware, we can focus on its own logic in the controller, just like a background controller. I only need to focus on displaying the user list or article list, processing the added articles, and so on, instead of paying attention to whether the visitor is a valid background administrator, the work of permission verification should be handed over to the intermediate component. If it passes the middleware verification, it will be processed normally. if it fails, it will be redirected or other operations.
Laravel has many built-in middleware by default and is enabled by default. You can edit app/Http/Kernel. php to determine whether to enable the middleware. The self-developed middleware is also registered here.
The $ middleware array in app/Http/Kernel. php is a global middleware. that is to say, any route will be applied to these middleware, such as The CSRF verification middleware.
Sometimes we do not need global middleware. at this time, we can register a middleware to app/Http/Kernel. $ routeMiddleware array in the PHP file. The key name of the array is the middleware alias and the key value is a specific middleware class, as shown in figure
'Auth' => 'app \ Http \ Middleware \ AuthMiddleware '.
The following describes how to use specific middleware on a route.
We have registered an independent middleware in the $ routeMiddleware array in the app/Http/Kernel. php file. This middleware can be bound to a routing and routing group exclusively. You can define a route as follows:
Route::get('admin/profile', ['middleware' => 'auth', function(){ //}]);
When we access http: // yourdomain/admin/profile, we first go through the global middleware, and then go to app/Http/Kernel. the middleware defined in the $ routeMiddleware array of php is auth.
After talking about how to define the middleware class, what should it be like? The following code differs from the one in the document ):
ajax()) { return response('Unauthorized!', 401); } else { return redirect()->guest('admin/login'); } } view()->share('loign', true); return $next($request); }}
The above code is the written middleware, and the content in the handle method is the actual code of the middleware.
We can see that 18th ~ The 27 lines of code is probably a process of determining whether a user logs in. if there is no login, it determines whether the request is ajax type, for an ajax request, a json data indicating "you are not authorized" is returned (just understand it). if it is a standard request, it is redirected to the login interface.
If your authentication or pre-operation logic is passed in the middleware, remember to direct the request to the next middleware through the code return $ next ($ request) (28 rows in the preceding example, if there is no middleware in the end, the processing logic (such as the controller) will be implemented ).
The middleware mentioned above is a pre-operational middleware. what does it mean? It is the middleware before the actual processing logic. it is a front-end middleware. On the contrary, a middleware passed after the actual processing logic is a post-middleware.
The post-middleware structure is as follows:
We can see that the difference is that $ response = $ next ($ request) is added, and the return value also changes. It is easy to understand that the value returned by $ next ($ request) is the final response generated after countless specific processing logics of the request. this response is generally a bunch of html code (rendered view ), it may also be a json file. We can Final process the response in the middleware and return the final processing result.
Route GroupThis official document has a very detailed description, but it does not seem easy to understand. Let's talk about the applicable scenarios first.
A routing group is usually applicable to a certain type of routing group. The middleware and filters assigned to this routing group are applied to all routes in the group.
To put it bluntly, a routing group simplifies some routing definition processes. For example, I want to access the backend through the http: // yourdomain/admin/*** address. if I have two modules: user and article, their access requests must go through a middleware that verifies the permissions. I need to define the route as follows:
Route::get('admin/user', ['middleware' => 'authority', function() { // blablabla...}]);Route::get('admin/article', ['middleware' => 'authority', function() { // blablabla...}]);
Currently, there are only two routes. I have to write a few more admins and middleware is useless. However, when the system is large, each of them has to write the corresponding middleware separately, which is prone to errors and difficult to manage. At this time, you should use the routing group:
Route::group(['prefix' => 'admin', 'middleware' => 'authority'], function() { Route::get('user', function() { // blablabla... }); Route::get('article', function() { // blablabla... });});
At the same time, it is very easy to define sub-domain names using routing groups:
Route::group(['domain' => 'bbs.yourdomain.com'], function() { Route::get('topic', function() { // blablabla... }); Route::get('node', function() { // blablabla... });});
Sub-domain names can also have wildcards to achieve a more flexible structure. For example, I want every user on my website to have their own second-level domain names, like userA.yourdomain.com and userB.yourdomain.com. This can be written as follows:
Route::group(['domain' => '{username}.myapp.com'], function(){ Route::get('profile/{type}', function($username, $type) { // });});
You can use parameters to obtain the value of wildcard matching on the domain name.
In addition, the convenience of the routing group is quite rich. here, the meaning of the existence of the routing group is basically finished. other routing groups can be learned from the official documentation.