Ali Gajani
Ali Gajani

Reputation: 15091

How to add multiple route filters in Laravel 4.2 while using role:permission pattern?

I am having issues with using multiple route filters in Laravel 4.2 while using the pattern role:permission. I've attached my code below.

This doesn't work at all. When I change roles, it always give one 403 unauthorized. I want both moderator and administrator to access this route.

Perhaps there's a way to tell Laravel, "if the logged in user is either an administrator OR a moderator, then let them access this route".

Route::get('engage', [

    'as'   => 'engage_path',
    'before' => 'role:administrator',
    'before' => 'role:moderator',
    'uses' => 'ManagementController@showEngagement'
]);

This is my role filter.

Route::filter('role', function($route, $request, $role)
{
    if (Auth::guest() or ! Auth::user()->hasRole($role))
    {
        return Response::make('Unauthorized', 403);
    }

});

Upvotes: 1

Views: 724

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

I suggest you use some kind of delimiter, like a ; to pass in multiple roles.

'before' => 'role:administrator;moderator'

And change the filter:

Route::filter('role', function($route, $request, $value)
{
    if(Auth::check()){
        $user = Auth::user();
        $roles = explode(';', $value);
        foreach($roles as $role){
            if($user->hasRole($role)){
                return;
            }
        }
    }
    return Response::make('Unauthorized', 403);
});

Upvotes: 2

Related Questions