0
0
Laravelframework~5 mins

Route middleware in Laravel

Choose your learning style9 modes available
Introduction

Route middleware helps you run code before or after a web request. It controls access or changes requests easily.

To check if a user is logged in before showing a page.
To log details about each request for debugging.
To block users from certain pages based on roles.
To add security headers to responses.
To redirect users if they don't meet conditions.
Syntax
Laravel
Route::middleware('middlewareName')->group(function () {
    Route::get('/path', [Controller::class, 'method']);
});
Middleware names are registered in app/Http/Kernel.php.
You can apply middleware to single routes or groups of routes.
Examples
This route uses the 'auth' middleware to allow only logged-in users.
Laravel
Route::middleware('auth')->get('/dashboard', function () {
    return 'Welcome to your dashboard';
});
This group of routes requires users to be logged in and email verified.
Laravel
Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/profile', [ProfileController::class, 'show']);
    Route::post('/profile', [ProfileController::class, 'update']);
});
This route has no middleware, so it is open to all visitors.
Laravel
Route::get('/public', function () {
    return 'Anyone can see this';
});
Sample Program

This example shows two routes. The '/home' route uses a middleware called 'checkAge' to allow access only if the user meets age requirements. The '/open' route is open to all visitors without restrictions.

Laravel
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;

// Define a middleware named 'checkAge' in Kernel.php (assumed)

Route::middleware('checkAge')->get('/home', function () {
    return 'Welcome, you are old enough!';
});

Route::get('/open', function () {
    return 'This page is open to everyone.';
});
OutputSuccess
Important Notes

Middleware can stop a request and send a response before reaching the route.

You can create custom middleware with php artisan make:middleware MiddlewareName.

Always register your middleware in app/Http/Kernel.php to use it by name.

Summary

Route middleware runs code before or after a route handles a request.

Use middleware to protect routes or modify requests and responses.

Apply middleware to single routes or groups for easy control.