What are route middleware in Laravel?
Jun 21, 2025 am 12:30 AMLaravel's routing middleware is a mechanism for filtering HTTP requests. It is divided into global middleware and routing middleware, where the routing middleware is bound to a specific route, and is registered in app/Http/Kernel.php, such as 'auth' and 'admin', and is applied using the middleware method in the route definition or controller constructor; common uses include authentication checking, permission control, logging, request frequency limit, etc.; for example, creating CheckAdmin middleware and implementing judgment logic through the handle method; middleware also supports parameter passing, such as passing parameters through 'role:editor,admin' and receiving in the handle method to achieve more flexible permission control. Routing middleware can effectively improve project structure clarity and security.
Laravel's Route Middleware is a mechanism used to filter HTTP requests into an application. You can think of it as a door, and only requests that meet certain conditions can continue to move down through this door.
For example, you have a background management page that only hopes that users who have logged in can access it. At this time, you can use middleware to authenticate, and those who are not logged in can be blocked directly.
How to define and use routing middleware
In Laravel, middleware is divided into two types: global middleware and routing middleware. Here we focus on routing middleware , that is, the kind that is bound to a specific route.
You can register middleware in app/Http/Kernel.php
file. For example:
protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'admin' => \App\Http\Middleware\CheckAdmin::class, ];
Then add this middleware when defining the route:
Route::get('/dashboard', function () { // Only users who pass the auth middleware can access it})->middleware('auth');
Or you can add:
public function __construct() { $this->middleware('auth'); }
Common Middleware uses and examples
The most common uses of routing middleware include:
- Authentication check (such as
auth
) - Permission control (such as
admin
or not) - Logging or request timing
- Limit access frequency (such as preventing flashing interfaces)
To give a simple example, you want to make a middleware to determine whether the user has administrator privileges:
Create middleware with Artisan:
php artisan make:middleware CheckAdmin
Write logic in middleware:
public function handle($request, Closure $next) { if (! $request->user()->isAdmin()) { return redirect('/home'); } return $next($request); }
Register the middleware and apply it to the route and it is done.
Parameter transfer and more flexible control
Middleware can also receive parameters. For example, you have a middleware that is used to check the user role, and you can pass parameters like this:
->middleware('role:editor,admin')
These parameters can be obtained in the middleware code:
public function handle($request, Closure $next, $role) { if (! $request->user()->hasRole($role)) { return redirect('/no-access'); } return $next($request); }
This writing method is very practical when different permissions are required to be controlled according to different routes.
Basically that's it. The routing middleware does not seem complicated, but if used properly, it can greatly improve the structural clarity and security of the project, especially in terms of permission control.
The above is the detailed content of What are route middleware in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

InLaravel,policiesorganizeauthorizationlogicformodelactions.1.Policiesareclasseswithmethodslikeview,create,update,anddeletethatreturntrueorfalsebasedonuserpermissions.2.Toregisterapolicy,mapthemodeltoitspolicyinthe$policiesarrayofAuthServiceProvider.

In Laravel, routing is the entry point of the application that defines the response logic when a client requests a specific URI. The route maps the URL to the corresponding processing code, which usually contains HTTP methods, URIs, and actions (closures or controller methods). 1. Basic structure of route definition: bind requests using Route::verb('/uri',action); 2. Supports multiple HTTP verbs such as GET, POST, PUT, etc.; 3. Dynamic parameters can be defined through {param} and data can be passed; 4. Routes can be named to generate URLs or redirects; 5. Use grouping functions to uniformly add prefixes, middleware and other sharing settings; 6. Routing files are divided into web.php, ap according to their purpose

ToruntestsinLaraveleffectively,usethephpartisantestcommandwhichsimplifiesPHPUnitusage.1.Setupa.env.testingfileandconfigurephpunit.xmltouseatestdatabaselikeSQLite.2.Generatetestfilesusingphpartisanmake:test,using--unitforunittests.3.Writetestswithmeth

Artisan is a command line tool of Laravel to improve development efficiency. Its core functions include: 1. Generate code structures, such as controllers, models, etc., and automatically create files through make: controller and other commands; 2. Manage database migration and fill, use migrate to run migration, and db:seed to fill data; 3. Support custom commands, such as make:command creation command class to implement business logic encapsulation; 4. Provide debugging and environment management functions, such as key:generate to generate keys, and serve to start the development server. Proficiency in using Artisan can significantly improve Laravel development efficiency.

The main role of the controller in Laravel is to process HTTP requests and return responses to keep the code neat and maintainable. By concentrating the relevant request logic into a class, the controller makes the routing file simpler, such as putting user profile display, editing and deletion operations in different methods of UserController. The creation of a controller can be implemented through the Artisan command phpartisanmake:controllerUserController, while the resource controller is generated using the --resource option, covering methods for standard CRUD operations. Then you need to bind the controller in the route, such as Route::get('/user/{id

Laravelprovidesrobusttoolsforvalidatingformdata.1.Basicvalidationcanbedoneusingthevalidate()methodincontrollers,ensuringfieldsmeetcriterialikerequired,maxlength,oruniquevalues.2.Forcomplexscenarios,formrequestsencapsulatevalidationlogicintodedicatedc

CachinginLaravelsignificantlyimprovesapplicationperformancebyreducingdatabasequeriesandminimizingredundantprocessing.Tousecachingeffectively,followthesesteps:1.Useroutecachingforstaticrouteswithphpartisanroute:cache,idealforpublicpageslike/aboutbutno

The .env file is a configuration file used in the Laravel project to store environment variables. It separates sensitive information from code and supports multi-environment switching. Its core functions include: 1. Centrally manage database connections, API keys and other configurations; 2. Call variables through env() or config() functions; 3. After modification, the configuration needs to be refreshed before it takes effect; 4. It should not be submitted to version control to prevent leakage; 5. Multiple .env files can be created for different environments. When using it, you should first define variables and then call them in conjunction with configuration file to avoid direct hard coding.
