How to change default redirect URL of Laravel 5 Auth filter?(如何更改 Laravel 5 Auth 过滤器的默认重定向 URL?)
问题描述
默认情况下,如果我没有登录并尝试在浏览器中访问它:
By default if I am not logged and I try visit this in browser:
http://localhost:8000/home
它将我重定向到 http://localhost:8000/auth/login
如何更改以将我重定向到 http://localhost:8000/login
How can I change to redirect me to http://localhost:8000/login
推荐答案
我想在 Laravel 5.5 中做同样的事情.处理身份验证已移至 IlluminateAuthMiddlewareAuthenticate
,这会引发 IlluminateAuthAuthenticationException
.
I wanted to do the same thing in Laravel 5.5. Handling authentication has moved to IlluminateAuthMiddlewareAuthenticate
which throws an IlluminateAuthAuthenticationException
.
那个异常在IlluminateFoundationExceptionsHander.php
中处理,但是你不想改变原来的vendor文件,所以你可以用你自己的项目文件通过添加覆盖它它到 AppExceptionsHandler.php
.
That exception is handled in IlluminateFoundationExceptionsHander.php
, but you don't want to change the original vendor files, so you can overwrite it with your own project files by adding it to AppExceptionsHandler.php
.
为此,将以下内容添加到 AppExceptionsHandler.php
中 Handler
类的顶部:
To do this, add the following to the top of the Handler
class in AppExceptionsHandler.php
:
use IlluminateAuthAuthenticationException;
然后添加以下方法,根据需要进行
And then add the following method, editing as necessary:
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param IlluminateHttpRequest $request
* @param IlluminateAuthAuthenticationException $exception
* @return IlluminateHttpResponse
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login'); //<----- Change this
}
只需将 return redirect()->guest('login');
改为 return redirect()->guest(route('auth.login'));
或其他任何东西.
Just change return redirect()->guest('login');
to return redirect()->guest(route('auth.login'));
or anything else.
我想把它写下来,因为我花了 5 多分钟才弄明白.如果您碰巧在文档中找到了这个,请给我留言,因为我找不到.
I wanted to write this down because it took me more than 5 minutes to figure it out. Please drop me a line if you happened to find this in the docs because I couldn't.
这篇关于如何更改 Laravel 5 Auth 过滤器的默认重定向 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何更改 Laravel 5 Auth 过滤器的默认重定向 URL?
基础教程推荐
- 使用 PDO 转义列名 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01