如何更改 Laravel 5 Auth 过滤器的默认重定向 URL? [英] How to change default redirect URL of Laravel 5 Auth filter?

查看:35
本文介绍了如何更改 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.phpHandler 类的顶部:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆