laravel route filter to check user roles
Solution 1
Try the following:
filters.php
Route::filter('role', function()
{
if ( Auth::user()->role !==1) {
// do something
return Redirect::to('/');
}
});
routes.php
Route::group(array('before' => 'role'), function() {
Route::get('customer/retrieve/{id}', 'CustomerController@retrieve_single');
Route::post('customer/create', 'CustomerController@create');
Route::put('customer/update/{id}', 'CustomerController@update');
});
Solution 2
There are different ways you could implement this, for starts Route filters accept arguments:
Route::filter('role', function($route, $request, $value)
{
//
});
Route::get('someurl', array('before' => 'role:admin', function()
{
//
}));
The above will inject admin in your Route::filter, accessible through the $value parameter. If you need more complicated filtering you can always use a custom route filter class (check Filter Classes): http://laravel.com/docs/routing#route-filters
You can also filter within your controller, which provides a better approach when you need to filter based on specific controllers and methods: http://laravel.com/docs/controllers#controller-filters
Finally you can use something like Sentry2, which provides a complete RBAC solution to use within your project: https://cartalyst.com/manual/sentry
user1424508
Updated on July 21, 2022Comments
-
user1424508 almost 2 years
I am building a restful api in laravel 4 where there are users with different types of permission. I want to restrict access to different routes depending on the user role (which is saved in the user table in db)
How would I do that? Here is what I have so far (it's not working so far).
filters.php
//allows backend api access depending on the user's role once they are logged in Route::filter('role', function() { return Auth::user()->role; });
routes.php
Route::group(array('before' => 'role'), function($role) { if($role==1){ Route::get('customer/retrieve/{id}', 'CustomerController@retrieve_single'); Route::post('customer/create', 'CustomerController@create'); Route::put('customer/update/{id}', 'CustomerController@update'); } });
Is it possible that I'm writing the syntax wrong for a "group filter"?
-
user2943773 over 10 yearsExactly...It should works.... But if you need do it for multiple roles we need to change filter route like
Route::filter('role', function() { $roles = ['2','3','4']; if (!in_array(Auth::user()->role, $roles)) { return Redirect:to('/'); } });