Laravel Middleware

Laravel Middleware

Instructor-svgAl-Mamun Sarkar
Jul 08 , 2020

Laravel middleware is used to filter HTTP requests while entering into the application. I this lesson I will show how to create and use middleware in Laravel application.

 

Create a Middleware:

php artisan make:middleware TestMiddleware

TestMiddleware:

amespace App\Http\Middleware;

use Closure;

class TestMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}

 

Registering Middleware:

app/Http/Kernel.php
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,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        
        'test' => \App\Http\Middleware\TestMiddleware::class,
    ];

 

Using Middleware:

Route::get('path', function () {
    //
})->middleware('test');

 

Multiple middleware:

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

 

On Route Group:

Route::group(['middleware' => ['test']], function () {
    //
});

Route::middleware(['test', 'auth'])->group(function () {
    //
});

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram