0

I need to Add Level access to my website and i usually code my route like :

Route::get('/', array(
    'as' => 'home-view',
    'uses' => 'HomeController@viewHome'
));

/* Authenticated Group */
Route::group(array('before' => 'auth'), function(){
    Route::get('/', array(
        'as' => 'admin-view',
        'uses' => 'AdminController@viewAdmin'
    ));
}
/* Unauthenticated Group */
Route::group(array('before' => 'guest'), function(){
    Route::get('/signin', array(
        'as' => 'user-signin-get',
        'uses' => 'UserController@getSignIn'
    ));
}

i need to add level access as "user" or "admin". how i can do that filter route? as simple as possiple or what do you recommend?

GandhyOnly
  • 325
  • 2
  • 5
  • 18
  • I’d suggest you read up on route filters in the Laravel documentation: http://laravel.com/docs/routing#route-filters – Martin Bean Sep 11 '14 at 12:10

2 Answers2

1

You can have as many filters to a single route as you like. Consider this:

Route::group(array('before' => 'auth|hasAdminLevel'), function(){
    Route::get('/', array(
        'as' => 'admin-view',
        'uses' => 'AdminController@viewAdmin'
    ));
});

This will apply both the auth as well as the hasAdminLevel filter to your admin-view route. The hasAdminLevel route is a custom filter that you will need to define.

Update

hasAdminLevel is a custom filter, and can be defined like this:

Route::filter('hasAdminLevel', function() {
    if(Auth::user()->level != 'admin') {
        return Redirect::to('/');
    }
});

Where you place this is a little up to you, but a good place would be in the aptly named app/filters.php.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
0

I will assume that u have a users (id, username, etc), roles(id, name, etc), and user_role(user_id, role_id, etc) tables and the relationships properly setup in your models.

So you can create a new function in ur User Model to check if a user have a role.

public function hasRole($name) {
    foreach ($this->roles as $role) {
        if ($role->name == $name) return true;
    }
    return false;
}

Then you can create a filter for that:

Route::filter('role', function($route, $request, $role){
if( Auth::guest() or !Auth::user()->hasRole($role) ) {
    return Redirect::guest('/'); // whatever you want
}

});

And finally just apply the filter to your routes:

Route::group(['prefix' => 'admin', 'before' => 'role:the_role_name_you_want'], function(){
  // Your Routes here
});
Helder Lucas
  • 3,273
  • 2
  • 21
  • 26