Filters are one of the Larevel’s features that I like the most. It’s pretty straightforward – you need to run some chunk of code before or after some action. Recently I had to implement restrictions on route resources depending on user group. I use Sentry for user authentication and role management and this Laravel filter should check if user belongs to specified group and allow him access to route resource if he does.
One solution is to simply create a new filter for every group. But, I don’t like repetition. I wanted simple and elegant solution that meets my requirements, without unnecessary repetition of code. Here is solution I came up with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Route::filter('inGroup', function($route, $request, $value) { $values = explode( ';' , $value ); $user = Sentry::getUser(); $status = false; foreach ( $values as $val ) { $group = Sentry::findGroupByName($val); if ( $user->inGroup($group) ) { $status = true; } } if ( $status == false ) { return Redirect::route('index')->with('error' , 'You have no access to this resource!'); } }); |
Continue reading Laravel Filters: Route access depending on the user group