0

I am wanting to find out how I can pass in roles as an array because when I try to do this in my construct of my controller it always seems to only be Administrator.

The following is my app/controllers/UserscController.php

class UsersController extends BaseController {

    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('role:Administrator,Owner');
    }
}

The following is my app/filters.php

Route::filter('role', function($route, $request, $roles)
{
    if(Auth::guest() !== true)
    {
        if(!empty($roles))
        {
            $roles = explode(',', $roles);
            if(count($roles) > 0)
            {
                foreach($roles as $role)
                {
                    if (Auth::user()->role->role_name == $role)
                    {
                        return;
                    }
                }
            }
        }
        return Redirect::to('/youshallnotpass');
    }
});
1
  • Can you var_dump($roles) in your filter? Commented Jan 7, 2015 at 18:57

2 Answers 2

1

You can set the roles as a parameter in your controller. To load the roles into your filter you would do this:

Route::filter('role', function($route, $request)
{
    if(Auth::guest() !== true)
    {
        $roles = $route->parameter('roles');
        if(!empty($roles))
        {
            foreach($roles as $role)
            {
                if (Auth::user()->role->role_name == $role)
                {
                    return;
                }
            }
        }
        return Redirect::to('/youshallnotpass');
    }
});

Note: Before laraval 4.1 you would use: $roles = $route->getParameter('roles'); instead of $roles = $route->parameter('roles');

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

Laravel already explodes your filter parameters on the comma, to allow passing multiple parameters to a filter. So, in your case, you've actually passed two parameters to your filter: the first parameter has the value 'Administrator', and the second parameter has the value 'Owner'.

So, two quick options are:

Change the delimiter you're using in your string. In your controller: $this->beforeFilter('role:Administrator;Owner'); and then in your filter: $roles = explode(';', $roles);

Or, leave your controller code alone and use PHP's func_get_args() function in your filter:

Route::filter('role', function($route, $request)
{
    if(Auth::guest() !== true)
    {
        $roles = array_slice(func_get_args(), 2);
        foreach($roles as $role)
        {
            if (Auth::user()->role->role_name == $role)
            {
                return;
            }
        }
        return Redirect::to('/youshallnotpass');
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.