Laravel Middleware

Laravel middleware is the mechanism that controls the workflow between request and response.

When any request is fired, laravel middleware identifies it and processes it. According to the result, the middleware provides an appropriate response to the request.

For example, when the user sends a request to load the images, a middleware will check if the user is authenticated or not. If the user is authenticated then the middleware will load the images, otherwise, it will redirect the user to the login screen.

Creating and Defining Middleware

As usual in the laravel, you can create the middleware by executing the following command

php artisan make:middleware<middleware_name>

In the above command, you need to replace middleware-name with the name you want to give to your middleware.

For example, to create the middleware whose name is AgeMiddleware, you should run the below command

php artisan make:middleware AgeMiddleware

The middleware that you create can be seen at the app/Http/Middleware directory.

Registering Middleware

It is necessary to register the middleware in laravel to use them efficiently.

There are two types of middleware in the laravel,

  1. Global Middleware
  2. Route Middleware

Global Middleware

As the name suggests, global middleware will be executed during every HTTP request of the whole laravel application.

Global middleware is useful when you need to check certain conditions during every HTTP request such as authentication conditions.

A professional web app should check the authenticity of the user during each activity for security purposes.

Here, global middleware helps us to accomplish our tasks. We can register the middleware at the “app/Http/Kernel.php” file.

This file contains two properties $middleware and $routeMiddleware. Global middleware is registered inside $middleware array.

$routeMiddleware property is used to register route specific middleware.

You can define the global middleware as per the below lines

protected $middleware = [
   \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
   \App\Http\Middleware\EncryptCookies::class,
   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
   \Illuminate\Session\Middleware\StartSession::class,
   \Illuminate\View\Middleware\ShareErrorsFromSession::class,
   \App\Http\Middleware\VerifyCsrfToken::class,
];

Route Middleware

We can assign the route middleware to any special route.

You have to add the middleware with a key for your app/Http/Kernel.php file, and such middlewares are called route middleware.

Following is the code snippet where you can register or write route middleware along with its key.

protected $routeMiddleware = [
   'auth' => \App\Http\Middleware\Authenticate::class,
   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
   'userUploadImage' => \Illuminate\Routing\Middleware\userUploadImage::class,
];

In the above code, we have added the route middleware with the key like “userUploadImage

Middleware With Parameters

We can define parameters along with the middleware.

For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $next argument.

public function handle($request, Closure $next) {
   return $next($request);
}

Terminable Middlewares

These are special types of middlewares that start working right after any response is sent to the browser. The terminate method is used for achieving this. When a termination method is used in your project’s middleware, it gets called automatically after the browser response is sent.

<?php

namespace Illuminate\Session\Middleware;
use Closure;
class SessionBegin
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
    public function terminate($request, $response)
    {
        // thing to do while terminating the middleware
    }
}