Middleware
| Make middleware | |
| Handle requests | |
| Assign to routes | |
| Groups |
Make middleware
Middleware is a filter that inspects a request on its way to a route. Generate a fresh class with the canonical maker command and open the created file.
php artisan make:middleware EnsureAdmin
INFO Middleware created successfully.
Handle requests
Every middleware centers on a handle method that receives the request and a next closure. Call next to pass the request deeper, or return an early response to stop it.
The example below blocks visitors without an account with a 403 answer and lets everyone else continue.
use Closure; use Illuminate\Http\Request; public function handle(Request $request, Closure $next) { if ($request->user() === null) { abort(403); } return $next($request); }
Assign to routes
Middleware runs only where it is assigned, so attach it to the routes that need it. The middleware method on a route accepts the short name registered for the class.
Unassigned routes keep working exactly as before, which keeps the change local and safe.
use Illuminate\Support\Facades\Route; Route::get("/admin", function () { return "Admin area"; })->middleware("admin");
Groups
Groups bundle several middleware under one name so routes share common behavior. The web group handles sessions and csrf protection for browsers, while the api group stays light for tokens.
Custom groups collect project rules the same way: list them once and apply the group wherever it fits.
use Illuminate\Support\Facades\Route; Route::middleware("web")->group(function () { Route::get("/home", function () { return "Home"; }); });
Next: Service container
Article author: Arthur Isaev