0
votes

Couldn't find anything that specifically matches my situation. I have a route group defined as:

Route::group(['prefix' => 'api/v1/{access_token}'], function(){
    ...
}

The above group has several resource routes inside. I am trying to create a custom middleware that will validate the access_token parameter and return a 400 response if the parameter is not valid. I would like to be able to so something like this in my controllers:

class ProductController extends Controller {

    /**
     * Instantiate a new ProductController
     */
    public function __construct()
    {
        $this->middleware('verifyAccessToken');
    }
    ...
}

My question is not "how do I define custom middleware", but rather, how can I gain access to the access_token parameter from within the handle function of my custom middleware?

EDIT: While the question suggested as a duplicate is similar and has an answer, that answer seems to be outdated and/or unsatisfactory for what I am trying to accomplish.

3
Is there any particular reason you don't want to put the middleware on the route group its self?Ohgodwhy
@Ohgodwhy Nope. I usually prefer to define it in my controller, but I would be open to any solution that allows me to accomplish what I want.Vince
Have you tried my answer? It should be exactly what you are looking for.Thomas Kim

3 Answers

1
votes

You can just access it from your $request object using the magic __get method like this:

public function handle($request, Closure $next)
{
    $token = $request->access_token;
    // Do something with $token
}
0
votes

http://laravel.com/docs/master/middleware#middleware-parameters

For simple

public function yourmethod($access_token){
    $this->middleware('verifyAccessToken', $access_token);
}

I think you can't do it in __construct() method.

0
votes

Just stick the middleware on the Route::group

Route::group(['prefix' => 'api/v1/{access_token}', 'middleware' => 'verifyAccessToken'], function(){

});

Then in your middleware, as Thomas Kim pointed out, you can use the $request object to gain access to the token that was passed to the route.

public function handle($request, Closure $next)
{
    $token = $request->access_token;
    // Do something with $token
}