0

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.

Vince
  • 3,207
  • 1
  • 17
  • 28
  • Is there any particular reason you don't want to put the middleware on the route group its self? – Ohgodwhy Nov 12 '15 at 18:19
  • @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 Nov 12 '15 at 18:20
  • 2
    Possible duplicate of [Send route param to middleware as argument Laravel](http://stackoverflow.com/questions/32082758/send-route-param-to-middleware-as-argument-laravel) – ventaquil Nov 12 '15 at 18:25
  • Have you tried my answer? It should be exactly what you are looking for. – Thomas Kim Nov 12 '15 at 18:31

3 Answers3

1

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
}
Thomas Kim
  • 15,326
  • 2
  • 52
  • 42
0

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.

ventaquil
  • 2,780
  • 3
  • 23
  • 48
  • The point is to not have to duplicate the same code within every controller function... – Vince Nov 12 '15 at 18:23
  • 1
    @Vince try my question http://stackoverflow.com/questions/32082758/send-route-param-to-middleware-as-argument-laravel – ventaquil Nov 12 '15 at 18:25
0

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
}
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110