Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 683
Vladimir Avatar asked Feb 24 '15 17:02

Vladimir


People also ask

How do I change my Auth URL in Laravel?

To change the login URL's you should look for the Route::auth() method inside your routes/web. php and remove it.

How do I redirect back to original URL after successful login in Laravel?

Basically we need to set manually \Session::put('url. intended', \URL::full()); for redirect. That's what redirect()->guest('login') is for.

What is Auth :: Routes () in Laravel?

Auth::routes() is just a helper class that helps you generate all the routes required for user authentication. You can browse the code here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/Router.php instead.


1 Answers

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.

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.

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 } 

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.

like image 82
Moritz Ewert Avatar answered Sep 28 '22 03:09

Moritz Ewert