In Laravel, how to redirect to target page after being intercepted to Login

143 Views Asked by At

I am new to Laravel and have inherited a site to maintain. I'm still learning, but I have been able to stumble through a lot of fixes and changes (picking up a lot along the way) with the help of boards like this. The site has public and private pages (guest & user). Each has a dashboard (or Home, if you prefer). If the user bookmarks a private page, the site correctly sends them to the login page. However, after login is complete, it redirects them to the dashboard. How can I change it so that they will be redirected to the page they initially sought (bookmarked) after they are logged in?

I have found a few posts on this topic that seemed like they would be relevant, but either the code samples they referenced didn't resemble mine (at all), or it just didn't work as they said it would, didn't fix my problem.

2

There are 2 best solutions below

0
turbowine On

Figured it out,in my version of Laravel, I had to do this in class AuthenticatedSessionController (replacing the commented out line with the line above it):

public function store(LoginRequest $request)
{
    $request->authenticate();
    $request->session()->regenerate();
    return redirect()->intended('/dashboard');
    //return redirect('/dashboard');
}

The hard part for me was figuring out where to do this. Thanks All! UPDATED: Added this reference per suggestion: The docs about intended function.

2
Utmost Creator On

UPDATE 2024-01-21: Code updated to indicate proper placement; added detailed descriptions for clarity. Or in laravel 7 or later using Guard + override of login @utmostcreator

The store method you used is typically responsible for handling the login request, authenticating the user, and then redirecting them.

Your current implementation of the store method uses redirect()->intended('/dashboard'), which means it will redirect the user to the intended URL they were trying to access before being intercepted for login.

You can check comments' links which I belive you can find quite useful as well. And mentioning laravel version would be very useful as well, as it may have changed between different versions.

An alternative method can be used as:

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    // Other methods and properties...

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        // Perform any actions needed after a user is authenticated
        return redirect()->intended('/defaultPath'); // Replace '/defaultPath' with your desired default path
    }
}

When you are done verifying or charging the user or whatever you need to do to grant access to the protected page you simply use the code below instead of a regular redirect. return redirect()->intended(); This redirect will look for a specific session property that was set previously(if there was any). If for some reason the session data is missing you can pass a default redirect url as a parameter: return redirect()->intended('/default-page'); Laravel's authentication is using this type of redirect to bring you back if you visited a page protected by the auth guard and you were not logged in. [souce link]

  • authenticated - It acts as a built-in hook in Laravel's authentication flow, which is called immediately after a user is authenticated but before the response is sent. It has less customization and is used for handling actions post-authentication and doesn't allow for additional customization within the login process itself.

  • store - has direct control over the login process within the store method, which is the default method for handling login requests in Laravel's LoginController, and it allows you to customize your login process, such as performing extra actions or checks before or after authentication.

  • AuthenticatesUsers trait with authenticated method - https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php

  • for laravel version 7 or newer you should check out this post - Trait 'Illuminate\Foundation\Auth\AuthenticatesUsers' not found on laravel 7x

Define a new guard. You can use the existing user provider or create a new one if necessary config/auth.php:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    // Add your custom guard here
    'custom' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

Implement Custom Authentication Logic in app/Http/Controllers/Auth/LoginController.php:

// app/Http/Controllers/Auth/LoginController.php

use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::guard('custom')->attempt($credentials, $request->filled('remember'))) {
            // Custom behavior after successful login using the custom guard
            return redirect()->intended('/dashboard'); // Replace '/dashboard' with your desired route
        }

        // Handle failed login
        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }

    // Other methods...
}

Using the custom guard in routes or controllers (You can specify the custom guard in your routes or controllers to protect them. For example, use middleware to specify the guard):

// In a routes file
Route::middleware('auth:custom')->group(function () {
    // Protected routes
});

// In a controller constructor
public function __construct()
{
    $this->middleware('auth:custom');
}

When logging out, make sure to use the custom guard to properly terminate the user's session in case you modified something.

public function logout(Request $request)
{
    Auth::guard('custom')->logout();
    // Additional logout logic...
    return redirect('/login');
}

By defining and using a custom guard, you have more flexibility in how users are authenticated and how their sessions are managed.