This article brings you relevant knowledge about laravel, which mainly introduces related issues about middleware, including what is middleware, custom middleware, etc., middleware It provides a convenient mechanism for filtering HTTP requests entering the application. Let's take a look at it. I hope it will be helpful to everyone.
【Related recommendations: laravel video tutorial】
Middleware Provides a convenient mechanism for filtering HTTP requests entering an application. For example, Laravel has a built-in middleware to verify whether the user is authenticated (such as logged in). If the user is not authenticated, the middleware will redirect the user to the login page; if the user has been authenticated, the middleware will allow the request. Continue forward to the next step. In addition to authentication functions, middleware can be used to handle many other tasks. For example, CORS middleware can add appropriate headers (cross-domain) to responses leaving the site; log middleware can record all requests
entering the site, making it easier for us to build a system log system.
Lavarel comes with some middleware, including authentication, CSRF protection middleware, etc. All middleware is located in the app\Http\Middleware directory.
Steps:
php artisan make:middleware middleware name
For example, some items in the amusement park require 12 years old or a height of more than 1.4 meters to play.
php artisan make:middleware CheckAge
Closure is a closure function
$request is used to receive application requests Array
$next Pass the request to the application
$next($request) Pass the request to the application
public function handle(Request $request, Closure $next) { if($request->age <h3>Register middleware</h3><p>Open app\Http The configuration file Kernel.php</p><blockquote><p>$middleware in the folder configures global middleware. All http requests need to go through the middleware we defined. <br> $middlewareGroupsMiddleware Group<br> $routeMiddleware Define alias</p></blockquote><pre class="brush:php;toolbar:false">'age' => \App\Http\Middleware\CheckAge::class
//中间件Route::get('middleware/{age}',function () { return "你的年龄符合要求";})->middleware('age');
http://www.la.com/middleware/1
http://www.la.com/middleware/12
【Related recommendations: laravel video tutorial】
The above is the detailed content of Detailed explanation of laravel middleware basics. For more information, please follow other related articles on the PHP Chinese website!