@mac
To redirect a user after login in Laravel, you can use the redirect
helper function. Here's an example of how to use it:
1 2 3 4 |
if (Auth::attempt($credentials)) { // Authentication passed... return redirect()->intended('dashboard'); } |
In this example, the user will be redirected to the dashboard
route if the login credentials are valid. If you want to redirect the user to a different route, simply replace dashboard
with the desired route name.
If you want to redirect the user to a specific URL instead of a route, you can use the to
method:
1
|
return redirect()->to('https://example.com'); |
You can also pass a second argument to the to
method to specify the status code for the redirect. For example:
1
|
return redirect()->to('https://example.com', 302); |
This will send a 302 (Found) status code with the redirect.
@mac
In Laravel, you can redirect to a specific route after the user successfully logs in by using the redirectTo
property in the LoginController
class.
First, make sure that the LoginController
has the RedirectsUsers
trait included. This trait provides the necessary logic for redirecting after the login.
Next, locate the LoginController
file located at app/Http/Controllers/Auth/LoginController.php
. Look for the redirectTo
property and modify it accordingly:
1
|
protected $redirectTo = '/dashboard'; // Change '/dashboard' to the desired route |
In this example, the user will be redirected to the /dashboard
route. You can update the value to any route within your application.
If you want to define the redirect route dynamically, you can override the redirectTo
method in the LoginController
class. For example:
1 2 3 4 |
protected function redirectTo() { return '/dashboard'; } |
You can also redirect the user to the previous page they were on before being redirected to the login page by using the intended
method. This method will store the intended URL in the session and redirect the user to that URL after a successful login.
To use the intended
method, you need to include the RedirectsUsers
trait and call the intended
method within the sendLoginResponse
method of the LoginController
class.
Here's an example of how to use the intended
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
use IlluminateHttpRequest; use IlluminateSupportFacadesAuth; use IlluminateFoundationAuthRedirectsUsers; class LoginController extends Controller { use RedirectsUsers; // ... protected function sendLoginResponse(Request $request) { $request->session()->regenerate(); $this->clearLoginAttempts($request); return $this->authenticated($request, $this->guard()->user()) ?: redirect()->intended($this->redirectPath()); } } |
By including redirect()->intended($this->redirectPath())
in the sendLoginResponse
method, Laravel will redirect the user to the intended URL saved in the session, or fallback to the default redirect path specified by the redirectPath
method in the LoginController
class.