Laravel Middleware

Laravel use middleware to filter HTTP requests. Each request which is interacting with application can be identify either to process or perform other action. Some of basic uses of middleware in Laravel applications are as follows.

  1. Check Authentication
  2. Log HTTP Requests

1. Check Authentication using Middleware

Middleware are helpful to filter authenticated requests. It check whether the coming request is coming from authenticated user, if it is then the request will process otherwise Middleware will redirect this request to Login page.

2. Log HTTP Requests

It is an easy way to log each request coming to application using Middleware, for this purpose we have to register Middleware in pp/Http/Kernel.php class.

Available Middleware in Laravel Application

There are some built-in middleware available in new Laravel application are.

  1. Authenticate
  2. CheckForMaintenanceMode
  3. EncryptCookies
  4. RedirectIfAuthenticated
  5. TrimStrings
  6. TrustProxies
  7. VerifyCsrfToken

Create New Middleware

New user defined middleware can also be created using artisan command. For this purpose we have to run the make:middleware command in such a way.

php artisan make:middleware testMiddleware

A newly created middleware will contain the follwing lines of code by defautl.

<?php

namespace App\Http\Middleware;

use Closure;

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

After creating this new middleware component we cannot use it without registering it in Kernel.php file. There are two commonly used method for registering middleware in Kernel.php.

  1. Register for Each HTTP Request
  2. Register for Specified Routes

1. Register for every HTTP requests

If we want to endorse our newly created middleware for every HTTP request then we have to register it in protected $middleware list in such a way.

protected $middleware = [
        \App\http\Middleware\testMiddleware::class,  // This is new middleware
    ];

This will filter every request using this middleware.

2. Register for Specific Routes

We can also limit middleware for only specied routes by adding this in protected $routeMiddleware list. This all will done using Kernel.php file. After adding this line protected $routeMiddleware will look like this.

protected $routeMiddleware = [
        'test' => \App\http\Middleware\testMiddleware::class,
    ];

We can also use any other name rather than test, depending on middleware.

Comments
Login to TRACK of Comments.