Php Laravel构造函数重定向不起作用
我有一个具有多个方法的控制器,我需要在每个方法开始时添加一个特定的授权检查。所以我想把这个签入构造函数作为Php Laravel构造函数重定向不起作用,php,laravel,laravel-4,Php,Laravel,Laravel 4,我有一个具有多个方法的控制器,我需要在每个方法开始时添加一个特定的授权检查。所以我想把这个签入构造函数作为 class AdminController extends BaseController { public function __construct() { $this->isAuthorized(); } protected $layout = "layouts.main"; private function isAuthorized() {
class AdminController extends BaseController {
public function __construct() {
$this->isAuthorized();
}
protected $layout = "layouts.main";
private function isAuthorized() {
if (!Session::get('userId')) {
echo "inside check"; // checking for debug purpose
return Redirect::to('login');
}
}
/**
* Admin dashboard view after authentication.
*/
public function getDashboard() {
$this->layout->content = View::make('admin.dashboard');
}
}
它不工作,它只是在会话检查中打印消息并加载仪表板页面,而不是重定向回登录页面
我也试过类似的方法
public function getDashboard() {
$this->isAuthorized();
$this->layout->content = View::make('admin.dashboard');
}
当我尝试用这个奇怪的return语句调用这个方法时,它就工作了
public function getDashboard() {
return $this->isAuthorized();
$this->layout->content = View::make('admin.dashboard');
}
我是从你那里得到这个想法的。如何使用构造函数方法实现这一点?返回一个
重定向
以执行它只能从路由、控制器操作和过滤器中执行。否则,您必须调用send()
确保使用照明\路由\重定向器;并将其传递给构造函数。(拉威尔5.2)
事件,laravel在http头中设置重定向,但也会继续执行请求,就像并没有重定向一样。因此,解决方案是在重定向后使用die()
public function __construct(Request $request, \Illuminate\Routing\Redirector $redirecor)
{
//$bool = ...
if (false == $bool) {
$redirecor->action('MyController@myAction')->send() ;
die();
}
}
在Laravel构造函数中使用
->send()
。为什么不使用路由筛选器?这就是它们的设计目的。在将标题发送到浏览器(在本例中为重定向指令)之前,不能打印任何内容。移除回声,它可能会工作。我只是通过回声来检查它是否在内部检查,即使移除回声也不起作用。我在拉雷维尔只有一周大,如果这些过滤器是为实现这一点而设计的,那么我必须使用它们。我强烈建议您使用它们:)我还建议您阅读文档中有关Laravel内置身份验证的部分。实际上,我只接受在我的管理面板中使用谷歌登录,所以我避免使用内置身份验证,我已经读过这篇文章,它真的很棒。谢谢你也指导我。但是请记住,仅仅因为它有效并不意味着你就应该这样做(如果有更好的方法的话);)四年后,在当前的Laravel 5.6中不再有过滤器。相反,请查看中间件:
use Illuminate\Routing\Redirector;
class ServiceController extends Controller {
public function __construct(Request $request, Redirector $redirect) {
$this->service = Auth::user()->Service()->find($request->id);
if (!$this->service) {
$redirect->to('/')->send();
}
}
public function __construct(Request $request, \Illuminate\Routing\Redirector $redirecor)
{
//$bool = ...
if (false == $bool) {
$redirecor->action('MyController@myAction')->send() ;
die();
}
}
redirect()->route('named-route')->send();
return redirect()->route('named-route');