Laravel:使用一个规则过滤多个控制器的最简单方法?
I have a users table with a field called 'role', 0 - regular users, 1 - admin.
I have multiple controllers that only the admin uses. What is the easiest way to only allow users with a role of 1 to use them? I will have all these controllers in a folder called 'admin'.
Currently I have an if test in my routes.php file like this
if(Auth::user()->role == 1) {
Route::resource('someRes', 'someResController');
}
But I have come to realize this is the wrong way to do it.
我有一个带有“role”字段的用户表,0 - 普通用户,1 - admin。 p>
我有多个只有管理员使用的控制器。 仅允许角色为1的用户使用它们的最简单方法是什么? 我将所有这些控制器放在一个名为“admin”的文件夹中。 p>
目前我的routes.php文件中有if测试,如 p>
if(Auth :: user() - > role == 1){
Route :: resource('someRes','someResController');
}
code> pre>
但我来了 要意识到这是错误的做法。 p>
div>
As mentioned, use route groups, allows you to group routes and filter:
Route::group(array('before' => 'checkUser'), function()
{
Route::resource('someRes', 'someResController');
Route::resource('anotherRes', 'anotherResController');
});
Then in your filters:
Route::filter('checkUser', function()
{
if(Auth::user()->role !== 1)
{
return Redirect::route('loginRoute')->with('message', 'Authorization required');
}
});
Just transform your check into route filter: http://laravel.com/docs/routing#route-filters
Then group restricted routes with route group and apply that filter on it: http://laravel.com/docs/routing#route-groups