How to Use Route Middleware in Laravel: Simple Guide
In Laravel, you use
route middleware by assigning middleware classes to routes or route groups in your routes/web.php or routes/api.php files. Middleware acts as a filter that runs before or after a request, allowing you to control access or modify requests easily.Syntax
Middleware is assigned to routes using the middleware method or the middleware key in route groups. You specify the middleware name registered in app/Http/Kernel.php.
- Route middleware: Applied to a single route.
- Group middleware: Applied to multiple routes in a group.
php
Route::get('/profile', function () { // Your code here })->middleware('auth'); Route::middleware(['auth', 'verified'])->group(function () { Route::get('/dashboard', function () { // Your code here }); Route::get('/settings', function () { // Your code here }); });
Example
This example shows how to protect a route with the built-in auth middleware to allow only logged-in users to access the /dashboard page.
php
<?php use Illuminate\Support\Facades\Route; Route::get('/dashboard', function () { return 'Welcome to your dashboard!'; })->middleware('auth');
Output
If the user is logged in, the page shows: Welcome to your dashboard!
If not logged in, Laravel redirects to the login page.
Common Pitfalls
- Forgetting to register custom middleware in
app/Http/Kernel.phpcauses Laravel to not recognize it. - Using middleware names that don't exist or have typos leads to errors.
- Applying middleware to routes without considering order can cause unexpected behavior.
- Not grouping routes when applying multiple middleware can cause repetitive code.
php
/* Wrong: Middleware not registered in Kernel.php */ Route::get('/admin', function () { return 'Admin area'; })->middleware('checkAdmin'); /* Right: Register middleware in Kernel.php and then use it */ // In app/Http/Kernel.php // protected $routeMiddleware = [ // 'checkAdmin' => \App\Http\Middleware\CheckAdmin::class, // ]; Route::get('/admin', function () { return 'Admin area'; })->middleware('checkAdmin');
Quick Reference
Use this quick reference to remember how to apply middleware in Laravel routes:
| Action | Syntax Example |
|---|---|
| Apply middleware to a single route | Route::get('/path', fn() => '')->middleware('middlewareName'); |
| Apply multiple middleware to a route | Route::get('/path', fn() => '')->middleware(['first', 'second']); |
| Apply middleware to a group of routes | Route::middleware(['auth'])->group(function () { /* routes */ }); |
| Register custom middleware | Add to $routeMiddleware in app/Http/Kernel.php |
Key Takeaways
Assign middleware to routes using the middleware method or route groups.
Always register custom middleware in app/Http/Kernel.php before use.
Middleware runs before the route logic to filter or modify requests.
Use route groups to apply middleware to multiple routes efficiently.
Check middleware names carefully to avoid errors.