Redirect if authenticated logic in Laravel's built-in auth?
High level answer: the purpose of RedirectIfAuthenticated
is to keep an already authenticated user from reaching the login or registration routes/views since they're already logged in.
Test: bookmark the login view. Then login. Close the browser or window. Open the login bookmark. You'll go straight to user's home or where ever specified in RedirectIfAuthenticated
.
For purposes of the LoginController, create a redirecTo()
method, which is what the redirectPath()
method looks for to see if you have customized the redirect.
// example
public function redirectTo()
{
switch (auth()->user()->role) {
case 'foo':
return route('foo.home');
case 'bar':
return route('bar.home');
default:
auth()->logout();
return route('web.welcome');
}
}
You are not using the middleware correctly. This piece of code will fire everytime you send a request when you are logged in.
To change the redirect location after login you can override the redirectPath()
method in your AuthController. (You can find the original method in vendor/laravel/framework/src/Illuminate/Foundation/Auth/RedirectsUsers.php
)
This would look something like this:
...
public class AuthController extends Controller {
...
public function redirectPath()
{
if(Auth::user()->sign_up_complete == 1) {
return '/';
} else {
if(Auth::user()->step_one_complete == 0) {
return '/register/step-1';
} elseif(Auth::user()->step_two_complete == 0) {
return '/register/step-2';
} else {
return '/';
}
}
}
// The rest of the class implementation.
}
Note: I've replaced the $this->auth()
method with the Facade alternative (Auth::
). Just because I am not sure if the AuthController has an auth()
method.
Solution is in Mark Walet's answer, but need little correction. Return should be a string:
public class AuthController extends Controller {
...
public function redirectPath()
{
if(Auth::user()->sign_up_complete == 1) {
return '/';
} else {
if(Auth::user()->step_one_complete == 0) {
return '/register/step-1';
} elseif(Auth::user()->step_two_complete == 0) {
return '/register/step-2';
} else {
return '/';
}
}
}
// The rest of the class implementation.
}