laravel
Laravel Tutorials – Laravel Middleware

Laravel Tutorials – Laravel Middleware

Middleware is another essential component of Laravel and provides the method to filter HTTP requests that get entered into your project. Let us assume a situation where this middleware of Laravel checks for an authenticated user of your software or project. In case the authentication is verified as valid, the middleware feature will let the user proceed with your project. There is another middleware name CORS in charge of adding appropriate headers to all of your responses.

Middleware can be defined as a middle-man or interface acting in coordination between a request and a response. As mentioned in the above test scenario, if the user is not authenticated, your project may redirect that user from the login.php to index.php page.

Define Middleware

You can create your middleware by running the syntax mentioned below:Syntax:

php artisan make:middleware<middleware_name>

Here, you have to replace the <middleware_name> with your middleware. You can see this path location app/Http/Middleware the middleware that you will be creating your project.Example:

php artisan make:middleware CheckUser

Registering Middlewares

Before using any middleware, you have to register it.Laravel provides two types of Middlewares. These are:

  • Global Middleware
  • Route Middleware

Global middlewares are those that will be running during every HTTP request of your application. In the $middleware property of your app/Http/Kernel.php class, you can list all the global middleware for your project.

When you want a middleware to specific routes, you have to add the middleware with a key for your app/Http/Kernel.php file, and such middlewares are called route middleware. $routeMiddleware, by default, holds entries for the middleware that are already incorporated in Laravel. For adding your custom middleware, you need to append them to the list and add a key of your choice.Example:

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

Middleware Parameters

Parameters can also be passed to middlewares. Various parameterized situations can be when your project has attributes like a customer, employee, admin, owner, etc. You want to execute different modules based on the user’s roles; for those situations, middlewares’ parameters become useful.Example:

public function handle($request, Closure $next, $profile)
   {
       if (! $request->user()->hasProfile($profile)) {
           // Next page
       }
       return $next($request);
   }
}

It would help if you created the Profile middleware by running the code mentioned below:

php artisan make:middleware ProfileMiddleware

The newly created middleware can be handled using the code: app/Http/Middleware/ProfileMiddleware.phpExample:

<?php

namespace App\Http\Middleware;
use Closure;

class ProfileMiddleware {
   public function handle($request, Closure $next, $Profile) {
      echo "Role: ".$Profile;
      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.Example:

<?php

namespace Illuminate\Session\Middleware;
use Closure;
class SessionBegin
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
    public function terminate($request, $response)
    {
        // tasks assigned within terminate method
    }
}

Next Chapter : Laravel – Controllers ❯

1 thought on “Laravel Tutorials – Laravel Middleware

Leave a Reply

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