l2t

Laravel middlewares

how to write laravel middleware efficiently

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. It is a layer between your request and controller. You can add additional verification or run some logic before the request goes to controller.

Followings are some of the use cases:

  • You want to check if user is logged in or not and redirect them to appropriate page
  • Restrict admin area vs public area etc...

You can also use middleware to run before or after http request.

How to create a middleware?

To create a middleware in laravel open your terminal window and run following command while being in the project root folder:

php artisan make:middleware IsAdmin

This command will place a new IsAdmin class within your app/Http/Middleware directory. Following is a sample middleware class:

<?php

namespace App\Http\Middleware;
use Closure;

class AdminAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = auth()->user();

        if (!auth()->check()) {
            return redirect(route('login'));
        }

        if (!$user->hasAdminAccess()) {
            return redirect('user/dashboard');
        }

        return $next($request);
    }
}

Above middleware basically checks to see if user is logged in and has admin access. If condition is met it will then go to controller otherwise it will redirect to login page.

Middleware can also be used to perform after task which means getting response from the controller and do something with the response. Following is a sample code where request goes to controller and get the data and then delivers via middleware.

You can add some additional logic before you render the response.

<?php

namespace App\Http\Middleware;
use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        // get data from the controller
        $response = $next($request);

        // do something here with response

        // render the response
        return $response;
    }
}

Assigning Middleware To Routes

Sometime you may want to attach your middleware to some routes. For example, you want to create a group of routes that pass through specific middleware.

Let say you have some admin routes that you grouped together and you want to run isAdmin middleware on all of your admin routes to make sure only admins are allowed to view certain routes.

To do this you first need to create a middleware as we saw earlier and then attaching this new middleware to route middlewares in  app/Http/Kernel.php​  file as below:

protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\IsAdmin::class,
    // other middleware goes here
];

Once you define your middleware in route middleware array you can now add following code to group your routes to use your new middleware:

// Login Protected Routes
Route::middleware(['web', 'admin'])->group(function () {
    // Place all your admin protected routes here ...
});

I hope you like this article please spread it with love. Thank you.