laravel 8 middleware example

    By: Thad Mertz
    2 years ago

    Today we are going to see how to create a middleware in Laravel 8.

    Middleware helps filtering http requests form entering your application.

    Now to see what middlewares your application has out of the box you can check

    "App\Http\Kernel.php" file looks like this.

     /**
         * The application's global HTTP middleware stack.
         *
         * These middleware are run during every request to your application.
         *
         * @var array
         */
        protected $middleware = [
            // \App\Http\Middleware\TrustHosts::class,
            \App\Http\Middleware\TrustProxies::class,
            \Fruitcake\Cors\HandleCors::class,
            \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
            \App\Http\Middleware\TrimStrings::class,
            \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        ];
    
    
        /**
         * The application's route middleware groups.
         *
         * @var array
         */
        protected $middlewareGroups = [
            'web' => [
                \App\Http\Middleware\EncryptCookies::class,
                \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
                \Illuminate\Session\Middleware\StartSession::class,
                // \Illuminate\Session\Middleware\AuthenticateSession::class,
                \Illuminate\View\Middleware\ShareErrorsFromSession::class,
                \App\Http\Middleware\VerifyCsrfToken::class,
                \Illuminate\Routing\Middleware\SubstituteBindings::class,
            ],
    
    
            'api' => [
                'throttle:api',
                \Illuminate\Routing\Middleware\SubstituteBindings::class,
            ],
        ];
    
    
        /**
         * The application's route middleware.
         *
         * These middleware may be assigned to groups or used individually.
         *
         * @var array
         */
        protected $routeMiddleware = [
            'auth' => \App\Http\Middleware\Authenticate::class,
            'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::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,
            'checkToken' => \App\Http\Middleware\CheckTokenForUser::class,
        ];
    
    


    Here we have middleware array where our middleware present. There is a custom middleware also present "CheckTokenForUser". Which is also in $routeMiddleware array with name "checkToken".


    Register Middle ware in Laravel


    In kernal.php there are 3 arrays, First $middleware array the top one. If you add your middleware in this array it will be used on each request to your application. So be very careful about that. Then we have second array $middlewareGroups, this one fires on groups. So if you add your middleware in this array under "web". then your middleware will be called on each web route. Now we want to call our middle ware on some routes so we add it in the third array which is $routeMiddleware, Any middleware under this array can be called on any group or individual route. But for that we will have to call the middleware on that route.


    This custom middleware has a handle method where we have the logic that filters the data. If you create a middleware you will have to write logic inside same function. Here is example

        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle(Request $request, Closure $next)
        {
            if($request->input('token') === '123'){
                return $next($request);
            }else{
                return abort(404);
            }
        }
    
    


    So if Token is equal 123 only then user can see the page.

    And we can apply this middleware to any route in web.php

    Route::get('/user', [HomeController::class, 'index'])->middleware('checkToken');
    

    Or to multiple routes at once like this

    Route::middleware(['checkToken', 'auth'])->group(function(){
    
        Route::get('/', [HomeController::class, 'index']);
    
        Route::get('/user', function(){
            return "User page";
        });
    
    
    });
    

    So when user navigates to "/?token=123" then user will see the page and if navigates to "/user?token=123" then user sees the message "User Page". In any other case if token is not 123 then user gets 404 error.


    For better practical understanding check our video guide.