A means for inspecting and filtering HTTP requests coming into our application is provided by middleware.

Creating a new middleware

Php artisan make:middleware TestMiddleware

Middleware is classified into three categories.

Global Middleware

Every HTTP request will trigger Global Middleware.

Let’s build some middleware.

php artisan make:middleware GloMiddleware

GloMiddleware is a new middleware that will appear in our middleware folder.

Now we must register GloMiddleware in Http/kernels.

 // The application's global HTTP middleware stack.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,
    \App\Http\Middleware\LoginCheckMiddleware::class,
    \App\Http\Middleware\GloMiddleware::class,
];

 

Now, use the handle method of GloMiddleware to echo something.

class GloMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        echo "Global Middleware";
        return $next($request);
    }
}

 

Now when we run the application we will see that each and every request will be return with “Global Middleware” string.

Groups middleware

We can define middleware groups using the Http/Kernel $middlewareGroups property.

protected $middlewareGroups = [ 'protect'=>[
    \App\Http\Middleware\SetDBMiddleWare::class,

 ], ]

We may utilize this ‘protect’ with groups along the way.

Route::middleware(['protect'])->group(function () {
    //Supplier route
    Route::post('/add_ie',[SupplierController::class,'store']);
    Route::get('/add_ie',function (){
                return view('layout/user/add_ie');

    });} );

Route Middleware

This one can be used with either a single or a group route.

Let’s make a new middleware and add it to $routeMiddleware.

php artisan make:middleware SingleMiddleware 

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,
    'singlemiddlee'=>\App\Http\Middleware\SingleMiddleware::class,
];

 

This is our SingleMiddleware

class SingleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        echo "Single Middleware";
        return $next($request);
    }
}

 

And in the route, we can use this middle as shown below.

Route::get('/', function () {
    return view('login');
})->middleware('singlemiddlee');

 

Or in a group, we can use this middle as shown below.

Route::middleware('singlemiddlee')->group(function () {
    Route::get('/', function () {
        return view('login');
    });
    Route::get('/singlemiddlee', function () {
        return view('login');
    });
});

 

Note: The AppProvidersRouteServiceProvider automatically applies the web and API middleware groups to the application’s corresponding routes/web.php and routes/api.php files out of the box.

 

<?php


class RouteServiceProvider extends ServiceProvider
{
    
    public const HOME = '/home';

    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));        
    }
}


 

Exclude Middleware:

If necessary, we can exclude some routes from the group using withoutMiddleware.

Route::middleware('singlemiddlee')->group(function () {
    Route::get('/', function () {
        //

    });
    Route::get('/profile', function () {
        //
    })->withoutMiddleware('singlemiddlee');
});

 

Sorting MiddleWare

We may arrange the loading order of middleware with $ middlewarePriority.

protected $middlewarePriority=[
    \App\Http\Middleware\secondmiddleware::class,
    \App\Http\Middleware\GloMiddleware::class,
    \App\Http\Middleware\SingleMiddleware::class,

];

 

Priority Order will be

1st  GloMiddleware::class

2nd secondmiddleware::class

3rd  SingleMiddleware::class

 

Because, even if we set the priority to this, Globalmiddleware will run first.

Middleware Parameter

Additional parameters can be passed to middleware.

Route::get('company', ['middleware' => 'singlemiddlee:owner', function () {
    return view('login');
}]);

 

public function handle(Request $request, Closure $next, $role)
{
     if($role=="owner") {
        // Redirect...
        echo "has one parameter";
    }
    echo "Single Middleware";
    return $next($request);
}

 

Terminate Middleware:

If the web server is using fastCGi, we can implement a terminate method in the middleware. The middleware will then terminate once the response has been sent to the browser.

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

    
    public function terminate($request, $response)
    {
      
    }
}

Resolving 

Laravel resolves a fresh or new instance of this middleware when the terminate method is called.

As a result, the handle and terminate method instances are not the same.

As a result, we must use singleton in AppServiceProvider.

use App\Http\Middleware\TerminatingMiddleware;

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
{
    $this->app->singleton(TerminatingMiddleware::class);
}

 

FastCGI:

FastCGI is a binary protocol used to connect interactive programs to a web server. FastCGI’s major goal is to decrease the cost associated with web server-to-CGI application interaction, allowing a server to process more web page requests per unit of time. CGI programs are any programs that take and return data.

 

By Navid Anjum

Full-stack web developer and founder of Laravelaura. He makes his tutorials as simple as humanly possible and focuses on getting the students to the point where they can build projects independently. https://github.com/NavidAnjum

2 thoughts on “Middleware in Laravel”

Leave a Reply

Your email address will not be published. Required fields are marked *