Middleware in Laravel is a vital component for handling HTTP requests. It allows developers to execute specific logic before a request reaches a controller or after the response leaves the application. Common use cases include authentication, logging, CSRF protection, and more. Middleware adds modularity and security to Laravel applications.
You can use Laravel's Artisan CLI to generate middleware. The following command creates a new middleware named CheckAge:
php artisan make:middleware CheckAge
This command will create a file called CheckAge.php inside the app/Http/Middleware directory.
After the middleware is generated, open the CheckAge file and add your custom logic to the handle method. Here is an example that checks whether the user's age meets the required threshold:
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return redirect('home');
}
return $next($request);
}
In this example, users under the age of 18 will be redirected to the home page.
Once the logic is implemented, register the middleware in the app/Http/Kernel.php file. You can define it as a route middleware like this:
protected $routeMiddleware = [
'age' => \App\Http\Middleware\CheckAge::class,
];
With this alias in place, the middleware can be easily applied to routes.
After registering, apply the middleware in your routing file. For example, in routes/web.php you might write:
Route::get('profile', function () {
// Profile page logic
})->middleware('age');
This ensures the CheckAge middleware runs before users can access the profile page.
Middleware in Laravel provides a flexible and elegant way to handle request filtering and logic execution. From creating and registering to applying in routes, the process is streamlined. Mastering middleware will help you build more secure and maintainable Laravel applications.