簡體   English   中英

如何從RedirectResponse對象強制進行Laravel 5.6重定向?

[英]How do I force a Laravel 5.6 redirect from a RedirectResponse object?

我有一個名為Item的自定義非口才類。 在構造函數中, Item嘗試通過我的應用進行身份驗證。 然后,我有一個Auth()方法來檢查身份驗證是否成功,如果不能,則觸發重定向。

public function Auth() {
    if (isset($this->authenticated)) {
        return $this;
    } else {
        return redirect('/auth');
    }
}

我使用Auth方法通過Item Facade靜態訪問Item 預期的結果是,如果對商品進行了身份驗證,我們將使用該商品作為變量進入索引。 如果不是,則將觸發重定向。

public function index() {
    $item = Item::Auth();
    return view('index',$item);
}

但是,如果未通過身份驗證,則所發生的只是將Laravel RedirectResponse對象傳遞到索引視圖。 我該如何強制將其重定向為實際觸發?

我曾想過但不喜歡的解決方案

if ($item instanceOf RedirectResponse)...在控制器中,但是感覺笨拙

$item = new Item; if ($item->authenticated)... $item = new Item; if ($item->authenticated)...這對控制器來說很好,但是我想從應用程序的多個部分觸發重定向,因此會有大量的代碼重用,感覺效率不高。

謝謝你的幫助。 在“立面”正面或觸發“重定向”對象。

您可以使用AuthenticationException處理這種情況:

public function Auth() {
    if (isset($this->authenticated)) {
        return $this;
    } 
    throw new AuthenticationException();
}

身份驗證異常將在JSON路由上生成登錄重定向或401錯誤。 您當然可以在App\\Exceptions\\Handler類中引發不同的異常並將其作為重定向進行App\\Exceptions\\Handler

例如:

public function Auth() {
    if (isset($this->authenticated)) {
        return $this;
    } 
    throw new ItemNotAuthorizedException(); //Custom class you need to create
}

Handler.php

 public function render($request, Exception $exception)
 {
    if ($exception instanceof ItemNotAuthorizedException) {
       return redirect("/auth");
    }
    return parent::render($request, $exception);
 }

注意:Laravel 5.6可能還允許異常實現自己的渲染功能,但是您應該參考該文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM