Question

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"?

Was it helpful?

Solution

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');


});

OTHER TIPS

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

From laravel 5.1.11 you can use the AuthServiceProvider: https://laravel.com/docs/5.1/authorization

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top