Laravel 8 Tutorial - Laravel Middleware

Published January 29, 2022

The Laravel middleware provides a connection between the request and the response. It also provides filtering capabilities. In this chapter, we will discuss the Laravel middleware. This chapter will cover the following topics:

  • Registering Middleware

  • The Middleware Parameters

  • The Terminable Middleware

 

1. Registering Middleware

The middleware class must be listed in the $middleware property of the app/Http/kernel.php class in order to be run within every HTTP request.

The middleware can also be assigned to any specific route within your application. To do so, you must assign the middleware a key within the app/HTTP/kernel.php file. By default, the $routeMiddleware property contains an already assigned middleware; however, it is not prohibited from listing any middleware you desire

/ Within App\Http\Kernel class...

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,

];

 

2. The Middleware Parameters

You can also add parameters to your middleware. For instance, if you want your application to validate that a user has been assigned a role before performing a given action, you need a middleware called EnsureUserHasRole that receives a role as a name with an additional argument.

You can pass the following parameters to the middleware after the $next argument

 

<?php

namespace App\Http\Middleware;

use Closure;

class EnsureUserHasRole

{

    /**

     * Handle the incoming request.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Closure  $next

     * @param  string  $role

     * @return mixed

     */

    public function handle($request, Closure $next, $role)

    {

        if (! $request->user()->hasRole($role)) {

            // Redirect...

        }

        return $next($request);

    }

}

 

To specify middleware parameters, you must separate the parameter values from the middleware using commas: Commas are used to separate multiple parameters

Route::put('/post/{id}', function ($id) {

    //

})->middleware('role:editor');

 

3. The Terminable Middleware

Middleware needs to perform some tasks after an HTTP response has been sent to the browser. When a terminate method is defined in middleware and your web server's FastCGI, the terminate method is automatically called after the response has been sent to the browser

 

<?php

namespace Illuminate\Session\Middleware;

use Closure;

class TerminatingMiddleware

{

    /**

     * Handle an incoming request.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Closure  $next

     * @return mixed

     */

    public function handle($request, Closure $next)

    {

        return $next($request);

    }

 

    /**

     * Handle tasks after the response has been sent to the browser.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Illuminate\Http\Response  $response

     * @return void

     */

    public function terminate($request, $response)

    {

        // ...

    }

}

 

Conclusion

Ultimately, we've had a look at the middleware in Laravel. We've covered middleware registration, middleware parameters, and terminable middleware

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

300 Views