How to register and assign middleware in Laravel

widget

Register middleware globally

In case you need middleware to run amid each HTTP request to your application, enlist the middleware class within the $middleware property of your app/Http/Kernel.php course.

Secure routes with middleware

In the event that you’d like to allot middleware to a particular route, you should begin by allocating the middleware a key in your application’s app/Http/Kernel.php record. By default, the $routeMiddleware property of this class contains sections for the middleware included with Laravel. You will add your middleware to this list and allocate it a key of your choice.

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

After the middleware has been characterized within the HTTP kernel, you will utilize the middleware method to allot middleware to a route, as shown below.

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

Free Resources