Laravel 4除了控制器构造函数中的过滤器 [英] Laravel 4 except filter in controller constructor
问题描述
当前,我有一个带有构造方法的AdminContoller,该方法处理一些以前的过滤器.是否可以对除一个以外的所有控制器方法进行事前过滤?
Currently I have an AdminContoller with a construct method handling some of the before filters. Is there a way to do a before filter on all controller methods except one?
我正在使用Entrust的角色和权限,但是这段代码使我陷入无限重定向循环.我根本没有以用户身份登录.因此,此代码应将我重定向到/admin/login URL,该URL附加到未过滤的AdminController @ adminLogin方法.但这不是吗?
I'm using Entrust for Roles and Permissions, but this code is throwing me into an infinite redirect loop. I'm not logged in as a user at all. So this code should redirect me to the /admin/login url which is attached to an unfiltered AdminController@adminLogin method. But it doesn't?
//AdminController.php文件
// AdminController.php file
class AdminController extends BaseController {
function __construct() {
// Is something like this possible?
$this->beforeFilter('admin', array('except' => array('adminLogin')));
$this->beforeFilter('csrf', array('on' => 'post'));
}
public function index()
{
return "Admin - Index";
}
public function adminLogin()
{
return "Admin Login Form";
}
// ... and many more methods
}
//Filter.php文件
// Filter.php file
Route::filter('admin', function()
{
if( !Entrust::hasRole('admin') ) // Checks the current user
{
return Redirect::to('/admin/login');
}
});
//Routes.php文件
// Routes.php file
Route::resource('admin', 'AdminController');
Route::get('/admin/login', 'AdminController@adminLogin');
推荐答案
在将新方法添加到资源丰富的控制器中后,您应该先在资源之前注册新方法.
As you've added a new method into a resourceful controller, you should register the new method first, before the resource.
例如
<?php // Routes.php
Route::get('/admin/login', 'AdminController@adminLogin');
Route::resource('admin', 'AdminController');
这样,您的before过滤器应可以像这样正常工作:
This way your before filters should work as you have then like this:
<?php // AdminController.php
class AdminController extends BaseController {
function __construct() {
$this->beforeFilter('admin', array('except' => array('adminLogin')));
$this->beforeFilter('csrf', array('on' => 'post'));
}
}
这篇关于Laravel 4除了控制器构造函数中的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!