在 Laravel 中使用路由过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13657921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using route filters in Laravel
提问by user225269
I'm trying to use route filters in laravel to check whether a specific user has an access to a page:
我正在尝试在 laravel 中使用路由过滤器来检查特定用户是否有权访问页面:
Route::filter('check_roles', function()
{
$current_url = URI::current();
$access = 0;
$nav = Session::get('navigation');
foreach($nav as $k => $n){
if(in_array($current_url, $n)){
$access = 1;
}
}
if($access == 0){
return Redirect::to('home');
}
//problem is if the user has access to the page a blank page is returned
});
I'm using it in a route like this:
我在这样的路线中使用它:
Route::get('admin/(:all)', array('before' => 'check_roles'));
The problem is if the user has access to the page a blank page is returned. How do I continue on with the default controller action if the user has access?
问题是如果用户有权访问该页面,则会返回一个空白页面。如果用户有权访问,我如何继续使用默认控制器操作?
回答by afarazit
Replace Route::get()
with Route::filter('pattern: admin/*', 'check_roles');
.
替换Route::get()
为Route::filter('pattern: admin/*', 'check_roles');
。
Now every time a request contains this pattern will be calling your check_roles filter.
I think that this is what you currently need and not a Route::get()
,
现在,每次包含此模式的请求都会调用您的 check_roles 过滤器。我认为这是您目前需要的,而不是Route::get()
,
You could use Route::get()
on individual pages like
您可以Route::get()
在单个页面上使用,例如
Route::get('supersecret', array('before' => 'check_roles'), function()
{ return View::make('mysecret') });
Route::get('supersecret', array('before' => 'check_roles'), function()
{ return View::make('mysecret') });
For more info Routing - Filters
欲了解更多信息路由 - 过滤器
Updating to reflect my suggestion on the comment.
更新以反映我对评论的建议。
You can create an Admin_Controller
that will extends your Base_Controller
and have your auth filter in the __construct()
.
您可以创建一个Admin_Controller
将扩展您的Base_Controller
并在__construct()
.
class Admin_Controller extends Base_Controller {
public function __construct()
{
parent::__construct();
$this->filter('before', 'auth');
}
}
Have this contoller registered in your start.php (search for Autoloader, where your base_controller is mapped).
在你的 start.php 中注册这个控制器(搜索 Autoloader,你的 base_controller 被映射到那里)。
And you could now extends your Admin_Controller
whenever you want to protected your area.
现在,您可以随时扩展您Admin_Controller
的区域来保护您的区域。
class Pages_Controller extends Admin_Controller {
// do cool stuff
}
Hope that helps
希望有帮助