Laravel 构造函数重定向不起作用

2022-08-30 14:24:46

我有一个具有多种方法的控制器,我需要在每个方法开始时添加特定的授权检查。所以我想把这个检查放在构造函数中,

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');
}

当我尝试用这个奇怪的返回语句调用此方法时,它的工作原理

public function getDashboard() {
    return $this->isAuthorized();
    $this->layout->content = View::make('admin.dashboard');
}

我是从这里得到这个想法的。如何使用构造函数方法实现此目的?


答案 1

返回 a 以执行它只能从路由、控制器操作和筛选器中执行。否则,您必须致电Redirectsend()

Redirect::to('login')->send();

但是,您应该为此使用过滤器


答案 2

确保使用照明\路由\重定向器;并将其传递给构造函数。(拉拉维尔 5.2)

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();
        }
    }

推荐