Search code examples
phplaravellaravel-4laravel-routingaccess-levels

Laravel 4 Route Level Access


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?


Solution

  • 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.