Anderson Silva
Anderson Silva

Reputation: 729

How to pass arguments from router to middleware in laravel 5?

I was facing an issue these days when I tried to pass arguments from my router to my middleware, to check if the authenticated user has the permissions to access that route. How can I pass an argument from routes to the middleware?

Upvotes: 1

Views: 1107

Answers (1)

Anderson Silva
Anderson Silva

Reputation: 729

I tried to do it and it works very well for me: In my routes files:

Route::group(['prefix' => 'agenda', 'middleware' => 'auth', 'permissions' => 'user.create|user.delete'], function() {
    //my routes here...
});

and inside the middleware:

class AuthMiddleware {
    private $r;
    private $guard;
    public function __construct(Router $r, Guard $g)
    {
        $this->r = $r;
        $this->guard = $g;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $route = $this->r->getCurrentRoute();
        $action = $route->getAction(); //$action['permissions'] is the string received from the routes file.
    }

Upvotes: 1

Related Questions