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

查看:128
本文介绍了如何更改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中做同样的事情.处理身份验证已移至Illuminate\Auth\Middleware\Authenticate并引发Illuminate\Auth\AuthenticationException.

I wanted to do the same thing in Laravel 5.5. Handling authentication has moved to Illuminate\Auth\Middleware\Authenticate which throws an Illuminate\Auth\AuthenticationException.

该异常在Illuminate\Foundation\Exceptions\Hander.php中处理,但是您不想更改原始供应商文件,因此可以通过将其添加到App\Exceptions\Handler.php来用您自己的项目文件覆盖它.

That exception is handled in Illuminate\Foundation\Exceptions\Hander.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 App\Exceptions\Handler.php.

为此,请将以下内容添加到App\Exceptions\Handler.phpHandler类的顶部:

To do this, add the following to the top of the Handler class in App\Exceptions\Handler.php:

use Illuminate\Auth\AuthenticationException;

然后添加以下方法,并根据需要进行

And then add the following method, editing as necessary:

/**
 * Convert an authentication exception into an unauthenticated response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
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天全站免登陆