Laravel/PHP-从子类返回/重定向 [英] Laravel/PHP - returning/redirecting from child class
问题描述
这是我的孩子控制者:
class VolunteersController extends \BaseController
{
public function index()
{
$this->checkForRoles(['admin']);
//list some secret stuff for admin
}
}
在我的基本控制器中,我这样做:
In my base controller I did this:
class BaseController extends Controller
{
protected function checkForRoles($roles)
{
foreach ($roles as $role) {
if (!(Auth::user()->hasRole($role))) {
return Redirect::to('/');
}
}
}
}
现在,我所期望的是,如果BaseController中的角色不是管理员,则行return Redirect::to('/');
会将用户重定向到首页.
Now what I expected was that the line return Redirect::to('/');
in BaseController would redirect the user to home page if his role is not admin.
但是不会发生. //list some secret stuff for admin
在任何情况下都会执行.
But it does not happen. //list some secret stuff for admin
gets executed in any case.
修改: 有人可能会奇怪,为什么我不使用过滤器.是的,所需的功能是过滤器,但显然过滤器尚不支持Laravel中的数组参数.如您所见,我需要将一组角色传递给该函数.
Some people may wonder, why am I not using filters. Well yeah, the desired functionality is of filters but apparently filters do not support array arguments in Laravel yet. And as you can see, I need to pass an array of roles to the function.
请帮助.
推荐答案
仅当VolunteersController :: index()返回"Redirect"时,重定向才会发生.在您的代码中没有.
The redirect will happen only if VolunteersController::index() will return a "Redirect". It does not do so in your code.
如果有的话
class VolunteersController extends \BaseController
{
public function index()
{
if ($res = $this->checkForRoles(['admin'])) return $res;
//list some secret stuff for admin
}
}
这篇关于Laravel/PHP-从子类返回/重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!