Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

php - How to change default redirect URL of Laravel 5 Auth filter?

By default if I am not logged and I try visit this in browser:

http://localhost:8000/home

It redirect me to http://localhost:8000/auth/login

How can I change to redirect me to http://localhost:8000/login

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wanted to do the same thing in Laravel 5.5. Handling authentication has moved to IlluminateAuthMiddlewareAuthenticate which throws an IlluminateAuthAuthenticationException.

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.

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
}

Just change return redirect()->guest('login'); to return redirect()->guest(route('auth.login')); or anything else.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...