0
0
Laravelframework~5 mins

Registering middleware in Laravel

Choose your learning style9 modes available
Introduction

Middleware helps control what happens before or after a web request. Registering middleware tells Laravel to use it in your app.

You want to check if a user is logged in before showing a page.
You need to log every request to your app.
You want to block certain IP addresses from accessing your site.
You want to add headers to all responses for security.
You want to run code after a request finishes, like clearing cache.
Syntax
Laravel
protected $routeMiddleware = [
    'name' => '\App\Http\Middleware\YourMiddleware',
];
This code goes inside the app/Http/Kernel.php file.
The key 'name' is how you refer to the middleware in routes.
Examples
This registers the built-in authentication middleware with the name 'auth'.
Laravel
protected $routeMiddleware = [
    'auth' => '\App\Http\Middleware\Authenticate',
];
This registers a custom middleware named 'checkAge' that you created.
Laravel
protected $routeMiddleware = [
    'checkAge' => '\App\Http\Middleware\CheckAge',
];
This adds middleware to a group called 'web' so all routes in that group use them.
Laravel
protected $middlewareGroups = [
    'web' => [
        '\App\Http\Middleware\EncryptCookies',
        'auth',
    ],
];
Sample Program

This example shows how to register two middleware in the Kernel and then use them on routes. The 'auth' middleware protects the '/profile' page, and the custom 'checkAge' middleware protects '/restricted'.

Laravel
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'checkAge' => \App\Http\Middleware\CheckAge::class,
    ];
}

// In routes/web.php

use Illuminate\Support\Facades\Route;

Route::middleware('auth')->get('/profile', function () {
    return 'User Profile Page';
});

Route::middleware('checkAge')->get('/restricted', function () {
    return 'Restricted Content';
});
OutputSuccess
Important Notes

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

You can register middleware globally or for specific routes.

Use meaningful names for middleware keys to keep your code clear.

Summary

Middleware controls request handling in Laravel.

Register middleware in Kernel.php to use it.

Apply middleware to routes by their registered name.