如果我想构建一个基本菜单,是否有一个函数可以用来测试给定用户是否可以访问命名路由?
如果没有,是否有从配置的路由中提取过滤器的功能?我正在看功能,但我没有看到如何首先“加载”每条路线。
答案 0 :(得分:1)
$route_names = array('ladger.create', 'ladger.update');
$routes = Route::getRoutes();
foreach ($route_names as $routeName) {
$route = $routes->getByName($routeName);
$beforeFilters = $route->beforeFilters();
print_r($beforeFilters);
}
exit;
Array
(
[auth] => Array
(
)
[permission] => Array
(
[0] => create_ladger
)
)
Array
(
[auth] => Array
(
)
[permission] => Array
(
[0] => edit_ladger
)
)
我的路线(根据例子):
Route::group(array('before' => 'auth|permission:ladger'), function(){
Route::post('/ladger/{group}/create', array( 'before' => 'permission:create_ladger', 'uses' => 'LadgerController@create', 'as' => 'ladger.create') );
Route::post('/ladger/{group}/update', array( 'before' => 'permission:update_ladger', 'uses' => 'LadgerController@update', 'as' => 'ladger.update') );
});
这取自我的一个项目。希望你能得到你正在寻找的想法。在foreach
循环中,以下行返回beforeFilters
:
$beforeFilters = $route->beforeFilters();
因此,您可以检查此数组以确定用户是否可以访问此路由。在我的情况下,我可以检查数组中的permission
以确定用户权限,如:
if( $beforeFilters && count($beforeFilters['permission']) ) {
// Has permission, check for specific one now...
}
这是我的permission
过滤器,它会在调度路由之前检查权限(如果有帮助):
// Filter for Permission Checking
Route::filter('permission', function($route, $request, $required_perm){
// Check if current user has all permissions
if(currentUser()->is('admin') || (count(currentUser()->permissions) == Permission::count())) return;
$currentUser = currentUser();
$user_perms = $currentUser->permissions;
// Check if user has any permission at all only if the
// $required_perm is 'any'. With any permission, user
// can go to the baack end/admin panel.
if($required_perm == 'any' && count($user_perms)) return;
// Check if user has any permission with given param,
// i.e. "create_user" allows access to the user page
// even if the user doesn't has other user related permissions
// like, "edit_user" or "delete_user", checks word "_user"
if($perms = $currentUser->hasAnyWith($required_perm)) return;
// Check if user has given permission, i.e. "delete_user"
if($currentUser->hasPermission($required_perm)) return;
// If comes here then not a valid user
// with required permission, so get off...
try {
return Redirect::back();
} catch (InvalidArgumentException $e) {
return Redirect::route('home');
}
});