Search code examples
phpfiltercontrollerlaravellaravel-3

Laravel Before Filter in the Controller with arguments


I have some troubles with filters in my controller and there parameters. Maybe one of you can help me out. Thank you. I have a controller similar to this one:

class Test extends Base_Controller
{

    public function __construct()
    {
        parent::__construct();    
        $this->filter('before', 'permission:destroy|auth')->only(array('show'));        
    }
    public function action_show($id)
    {
    }

and I defined a filter like this:

Route::filter('permission', function($permission)
{
    echo $permisson;

If I call now the controller, the $permission value of my filter is the $id which was passed through action_show($id) method. But when I have a Controller Method without a paramter everything works fine. How can I always get the filter parameter instead of the method argument?

Thanks for your help!


Solution

  • I can confirm what happens... when you add a filter to a controller, any arguments passed to the action are added to the front of the filter's arguments. You can use func_get_args() to confirm that this is the case.

    However, when you add a filter to a route this is not the case, the filter is run without any additional arguments.

    So I can see 2 choices here, either add the filter to the route...

    Route::get('test/(:any)', array('before' => 'permission:destroy|auth', 'use' => 'test@show'));
    

    Or modify your filter to use func_get_args(), like...

    Route::filter('permission', function()
    {
        $args = func_get_args();
        $permission = array_pop($args);
    
    });