Understanding laravel middleware

Laravel Middleware is a filtering mechanism because it act as a middleman between request and response or you can say its a “mediator” between your application and incoming request. Its actually a series of wrappers surrounding your application which arranges responses and requests in a beautiful manner.

laravel_blog_img

For example, Laravel has a middleware for verifying a user’s authentication. If the user authenticated, he/she will be redirected to home page, if not she will be redirected to the login page.

Custom middlewares can be added in laravel. The Cors middleware can be used for adding headers to your response. Permission middleware can be used to restrict different user roles for specific urls. There are several middlewares exist in laravel including Authentication and CSRF Protection.All middlewares are located in App\http\Middleware.

Creating Middleware

Creating middleware is easy in laravel by using artisan command. So use the make:middleware artisan command.

php artisan make:middleware checkGender

This command will create new class checkGender in App\http\Middlware Directory.In the middleware, we will restrict user who has gender male to access the route and redirect to dashboard.

 <?php

namespace App\Http\Middleware;

use Closure;

class CheckGender

{

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed

*/

public function handle($request, Closure $next)

{

if ($request->gender == ‘male’) {

return redirect(‘dashboard’);

}

return $next($request);

}

}

 

As you can see, if the given gender is male, the middleware will return an HTTP redirect to the dashboard; otherwise, the request will be passed further into the application.

Registering Middleware

Now that we’ve created a middleware, we need to let the application know the middleware exists. So, we need to register each and every middleware before using it.There are two types of Middleware in Laravel

  1. Global Middleware

  2. Route Middleware

The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.php. This file contains two properties $middleware and $routeMiddleware. $middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware. To register the global middleware, list the class at the end of $middleware property.

protected $middleware = [

\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

\App\Http\Middleware\EncryptCookies::class,

\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

\Illuminate\Session\Middleware\StartSession::class,

\Illuminate\View\Middleware\ShareErrorsFromSession::class,

\App\Http\Middleware\VerifyCsrfToken::class,

];

To register the route specific middleware, add the key and value to $routeMiddleware property.

protected $routeMiddleware = [

‘auth’ => \App\Http\Middleware\Authenticate::class,

‘auth.basic’ => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

‘guest’ => \App\Http\Middleware\RedirectIfAuthenticated::class,

];

We have created CheckGender in the previous example. We can now register it in route specific middleware property. The code for that registration is shown below.

protected $routeMiddleware = [

‘auth’ => \App\Http\Middleware\Authenticate::class,

‘auth.basic’ => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

‘guest’ => \App\Http\Middleware\RedirectIfAuthenticated::class,

‘gender’ => \App\Http\Middleware\CheckGender ::class,

];

Attaching a Middleware to a Route

Route::get(‘posts/{any}’, [‘middleware’ => ‘gender’, function () { return “Only female can go into application.”; }]);

To attach a middleware to your entire controller, specify the middleware in your constructor.

<?php namespace App\Http\Controllers;

 

use App\Http\Requests;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

 

class AuthController extends Controller

{

 

    public function __construct()

    {

        $this->middleware(‘auth’);

    }

 

    public function index()

    {

        return view(‘auth.index’);

    }

}

That’s it for now.