laravel route filter to check user roles

人走茶凉 提交于 2019-11-30 07:13:14
Anam

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


});

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!