我正在laravel 4中构建一个restful api,其中有许多用户拥有不同类型的权限.我想根据用户角色(保存在db中的用户表中)限制对不同路由的访问
我该怎么办?这是我到目前为止所做的(到目前为止还没有工作).
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'); } });
我是否有可能为"组过滤器"编写错误的语法?
有不同的方法可以实现这一点,对于启动路由过滤器接受参数:
Route::filter('role', function($route, $request, $value) { // }); Route::get('someurl', array('before' => 'role:admin', function() { // }));
以上将在您的Route ::过滤器中注入admin,可通过$ value参数访问.如果您需要更复杂的过滤,可以始终使用自定义路由过滤器类(选中过滤器类):http: //laravel.com/docs/routing#route-filters
您还可以在控制器中进行过滤,这在您需要根据特定控制器和方法进行过滤时提供了更好的方法:http: //laravel.com/docs/controllers#controller-filters
最后,您可以使用像Sentry2这样的东西,它提供了一个完整的RBAC解决方案,可以在您的项目中使用:https://cartalyst.com/manual/sentry
请尝试以下方法:
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'); });