Laravel Tutorial Index

Middleware and Security

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. The middleware feature will let the user proceed with your project if the authentication is verified as valid. There is another middleware name CORS in charge of adding appropriate headers to all of your responses.



Define Middleware

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

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 you will create for your project.

Example:

php artisan make:middleware CheckUser

Registering Middlewares

Before using any middleware, you have to register it.

Laravel provides two types of middleware. 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 middleware for specific routes, you must add the middleware with a key for your app/Http/Kernel.php file, which is 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 middleware. 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 helpful.

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.php

Example:

<?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 particular types of middleware 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 sending the browser response.

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
    }
}


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram