Friday, April 1, 2016

Passing parameters to Middleware in Laravel 5.1

Middleware is like a decorator that goes around our entire application request. It takes in a request, does some work, and spits out a response. And usually, it does that work consistently across every section of our application.

But what if we want to be able to customize exactly how the middleware is being processed for a given route, without creating a new middleware for every place it's customized?

Let's consider the most common example: Scoping authentication middleware based on roles. You want to, in the route definition, choose how the authentication middleware runs, by passing it a "role" parameter that defines which user role is required in order to access this route.

Using parameterized middleware in the route defintion #
When we are adding middleware to a route definition, we would normally set it like this:

Route::get('company', ['middleware' => 'auth', function () {
    return view('company.admin');
}]);

So, let's add in our parameter to show that the user must have the owner role:

Route::get('company', ['middleware' => 'auth:owner', function () {
    return view('company.admin');
}]);

Note that we can also pass multiple parameters as a comma-separated list:

Route::get('company', ['middleware' => 'auth:owner,view', function () {
    return view('company.admin');
}]);
Creating parameterized middleware #
So, how do we update our middleware to teach it to take parameters?

<?php

namespace App\Http\Middleware;

use Closure;

class Authentication
{
    public function handle($request, Closure $next, $role)
    {
        if (auth()->check() && auth()->user()->hasRole($role)) {
            return $next($request);
        }

        return redirect('login');
    }
}

Note that the handle() method, which usually only takes a $request and a $next closure, has a third parameter, which is our middleware parameter. If we passed in multiple parameters to our middleware call in the route definition, we can add more parameters to our handle() method:

public function handle($request, Closure $next, $role, $action)

We need to ensure that this middleware is registered in the HTTP Kernel as a routeMiddleware—there's no way we could pass parameters to a universal middleware.

1 comment:

  1. Thanks for sharing such as most useful information a for new Quickbooks we laso provide quickbooks service at
    quickbooks customer service phone number

    ReplyDelete