如何强制从RedirectResponse对象重定向Laravel 5.6?
How do I force a Laravel 5.6 redirect from a RedirectResponse object?
- lufc 问题:
- I have a custom non-Eloquent class called
Item
. In the constructor, theItem
attempts to authenticate with my app. I then have anAuth()
method to check whether the authentication was successful, and if not to fire a redirect. public function Auth() { if (isset($this->authenticated)) { return $this; } else { return redirect('/auth'); }}
- I use the
Auth
method to accessItem
statically via aItem
Facade. The intended outcome is that if the Item is authenticated, we proceed to the Index with that Item as a variable. If not the redirect would be triggered. public function index() { $item = Item::Auth(); return view('index',$item);}
- However, if not authenticated, all that happens is a Laravel
RedirectResponse
object is passed to the index view. How can I force that redirect to actually fire? - 我想过但不喜欢的解决方案
if ($item instanceOf RedirectResponse)...
in the controller, but this feels clunky$item = new Item; if ($item->authenticated)...
this is fine for the controller but I want to trigger the redirect from multiple parts of the app so there would be a lot of code re-use which doesn't feel efficient.- 谢谢你的帮助。要么在正面,要么触发重定向对象。
- I have a custom non-Eloquent class called
- 回答:
- apokryfos - vote: 0
- You can handle this case by using an
AuthenticationException
: public function Auth() { if (isset($this->authenticated)) { return $this; } throw new AuthenticationException();}
- The authentication exception will generate either a redirect to login or a 401 error on JSON routes. You can of course throw a different exception and handle it as a redirect in your
App\Exceptions\Handler
class - 例如:
public function Auth() { if (isset($this->authenticated)) { return $this; } throw new ItemNotAuthorizedException(); //Custom class you need to create}
- In
Handler.php
: public function render($request, Exception $exception) { if ($exception instanceof ItemNotAuthorizedException) { return redirect("/auth"); } return parent::render($request, $exception); }
- 注意:Laravel 5.6可能也允许异常实现其自己的渲染功能,但您应该参考文档了解这一点。
- You can handle this case by using an
- apokryfos - vote: 0