1. Introduction
The HTTP middleware provides a convenient mechanism for filtering HTTP requests into the application. For example, Laravel has built in a middleware to verify whether the user is authorized, if the user is not authorized, the middleware will redirect the user to the login page, or if the user is authorized, the middleware will allow the request to continue to move forward to the next operation.
Of course, in addition to authentication, middleware can also be used to handle more other tasks. For example, CORS middleware can be used to add the appropriate header (cross-domain) for the response to leave the site, and the log middleware can record all requests to enter the site.
Laravel framework comes with some middleware, including maintenance mode, authentication, CSRF protection middleware and so on. All middleware is located in the app/Http/Middleware directory.
2. Define Middleware
To create a new middleware, you can use the Artisan command make:middleware :
PHP Artisan Make:middleware Checkage
This command app/Http/Middleware creates a new middleware class in the directory, in which CheckAge we only allow more age than 200 the requested access route, otherwise we redirect the user to home :
<?phpnamespace app\http\middleware;use closure;class checkage{ /** * Return request Filter * * @param \ Illuminate\http\request $request * @param \closure $next * @return Mixed * /Public Function handle ( $request, Closure $next) { if ($request->input (' age ') <=) { return redirect (' home '); } return $next ($request);} }
As you can see, if the age<=200 middleware returns an HTTP redirect to the client, otherwise the request will be passed down. Passing the request down can be done by invoking the callback function and passing in $next $request .
The best way to understand middleware is to think of the middleware as a "layer" that the HTTP request must pass before it reaches the target action, and each layer examines the request and can reject it completely.
Middleware before/After
Whether a middleware is executed before or after a request depends on the middleware itself. For example, the following middleware performs some tasks before the request is processed:
<?phpnamespace app\http\middleware;use closure;class beforemiddleware{public function handle ($request, Closure $next) { //execute action return $next ($request);} }
However, the following middleware will perform its tasks after the request is processed:
<?phpnamespace app\http\middleware;use closure;class aftermiddleware{public function handle ($request, Closure $next) { $response = $next ($request); Execute action return $response; }}
3. Register Middleware
Global Middleware
If you want the middleware to be executed during each HTTP request, simply set the corresponding middleware class to app/Http/Kernel.php the array properties $middleware .
assigning middleware to routing
If you want to assign middleware to a specified route, you should first app/Http/Kernel.php assign the middleware to a shorthand key in the file, by default, the class's $routeMiddleware properties include the Laravel built-in portal middleware, add your own middleware, just append it to the back and assign it a Key, for example:
Within app\http\kernel class...protected $routeMiddleware = [ ' auth ' = = \illuminate\auth\middleware\ Authenticate::class, ' auth.basic ' = \illuminate\auth\middleware\authenticatewithbasicauth::class, ' Bindings ' = \illuminate\routing\middleware\substitutebindings::class, ' can ' and \illuminate\auth\ Middleware\authorize::class, ' guest ' = \app\http\middleware\redirectifauthenticated::class, ' Throttle ' = \illuminate\routing\middleware\throttlerequests::class,];
Once the middleware is defined in HTTP Kernel, it can be middleware assigned to a route using the method:
Route::get (' Admin/profile ', function () { //})->middleware (' auth ');
Use arrays to assign multiple middleware to routes:
Route::get ('/', function () { //})->middleware (' First ', ' second ');
The full class name can also be passed when the middleware is allocated:
Use App\http\middleware\checkage; Route::get (' Admin/profile ', function () { //})->middleware (Checkage::class);
Middleware Group
Sometimes you might want to distribute the relevant middleware into the same group by specifying a key name, making it easier to assign it to a route, which can be achieved by using HTTP Kernel $middlewareGroups properties.
Laravel comes with out-of-the-box web and api two middleware groups to include generic middleware that can be applied to Web UI and API routing:
/** * The application ' s route middleware groups. * * @var array */protected $middlewareGroups = [ ' web ' = = [ \app\http\middleware\encryptcookies::class, \illuminate\cookie\middleware\addqueuedcookiestoresponse::class, \illuminate\session\middleware\ Startsession::class, \illuminate\view\middleware\shareerrorsfromsession::class, \App\Http\Middleware\ Verifycsrftoken::class, \illuminate\routing\middleware\substitutebindings::class, ], ' API ' = [ ' throttle:60,1 ', ' Auth:api ', ],];
Middleware groups can be assigned to Routing and controller actions, using the same syntax as a single middleware. Again, the purpose of the middleware group is simply to make the implementation of routing multiple middleware once more simple:
Route::get ('/', function () { //})->middleware (' web '); Route::group ([' middleware ' + = [' web ']], function () { //});
Note: By default, RouteServiceProvider middleware groups are automatically web applied to routes/web.php files.
4. Middleware Parameters
The middleware can also receive additional custom parameters, for example, if the application needs to verify that the authenticated user has the specified role before performing the given action, you can create one CheckRole to receive the role name as an additional parameter.
Additional middleware parameters are passed into the $next middleware after the parameters:
<?phpnamespace app\http\middleware;use closure;class checkrole{ /** * Run request Filter * * @param \ Illuminate\http\request $request * @param \closure $next * @param string $role * @return Mixed * Translator http://laravelacademy.org * /Public Function handle ($request, Closure $next, $role) { if (! $request->user ()->hasrole ($role)) { //Redirect ... } Return $next ($request);} }
Middleware parameters can be specified by separating the middleware name and the parameter name when defining the route, and multiple middleware parameters can be separated by commas:
Route::p ut (' post/{id} ', function ($id) { //})->middleware (' Role:editor ');
5, the termination of the middleware
Sometimes the middleware may need to do some work after the HTTP response is sent to the browser. For example, Laravel's built-in "session" middleware writes session data to memory after the response is sent to the browser, and in order to achieve this, it needs to define a terminating middleware and add terminate methods to the middleware:
<?phpnamespace illuminate\session\middleware;use closure;class startsession{public function handle ($request , Closure $next) { return $next ($request); } Public function Terminate ($request, $response) { //store session data ... }}
terminateMethod will receive requests and responses as parameters. Once you have defined a terminating middleware, you need to add it to the list of global middleware for HTTP kernel.
When invoking a method on the middleware terminate , Laravel will remove the new instance of the middleware from the service container, and if you want to use the same middleware instance in the call and the method, you handle need to terminate singleton register the middleware in the container using the container's method.
HTTP Layer--middleware