Middleware in Laravel allows you to filter HTTP requests entering your application. It serves as a bridge between a request and a response, enabling you to apply specific checks or actions, such as authentication or logging. Let’s explore how to set middleware in Laravel.
1. Create Middleware
You can create a middleware using the Artisan command. This will generate a middleware file
in the app/Http/Middleware
directory.
php artisan make:middleware CheckAge
This command creates a file named CheckAge.php
in the
app/Http/Middleware
directory.
2. Define Middleware Logic
Open the CheckAge.php
file and define the logic in the handle
method. For example, to restrict access to users under 18:
public function handle($request, Closure $next) { if ($request->age < 18) { return redirect('home'); } return $next($request); }
3. Register Middleware
You need to register your middleware in the app/Http/Kernel.php
file. Add it to
the $routeMiddleware
array to use it with specific routes:
protected $routeMiddleware = [ 'check.age' => \App\Http\Middleware\CheckAge::class, ];
4. Apply Middleware to Routes
You can apply middleware to routes or groups in the routes/web.php
file. For
example:
Route::get('/profile', function () { // Profile logic here })->middleware('check.age');
Now, the middleware will check the user’s age before granting access to the profile page.