Laravel 8 + Jetsream: How to Redirect to Prior Page After Login?

Viewed 1394

I have a basic web page where I want the user to be able to click the login link, go through the login, and then be returned to that page (not the home page). The page has some features that can only be seen when the user is logged in.

I am having trouble with this, no matter what when I go to login it returns to the home page after authentication or whatever I have set as the constant, not the prior page.

Fortify.php has a home path that is a constant, so I can't update that with an expression either...

  'home' => RouteServiceProvider::HOME,

Here is the middleware RedirectIfAuthenticated.php, it is the standard Laravel and I'm wondering what would need to be updated.

    <?php

namespace App\Http\Middleware;

use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  ...$guards
     * @return mixed
     */
    public function handle(Request $request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                return redirect(RouteServiceProvider::HOME);
            }
        }

        return $next($request);
    }
}

I should note too, that if I add a middleware route to the page, as in the below example, then the process works correctly as far as returning the user back to the prior page.

Route::middleware(['auth:sanctum', 'verified'])->get('/agenda', function () {
    return view('agenda');
})->name('agenda');

However, I need the user to be able to view the agenda page, even if they are a guest... but, once logged in, they will be returned to the agenda page which will have some additional features. I can't seem to find in the documentation anything about this, unfortunately.

2 Answers

In AuthenticatesUsers.php

protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();

    $this->clearLoginAttempts($request);

    if ($response = $this->authenticated($request, $this->guard()->user())) {
        return $response;
    }

    return $request->wantsJson()
                ? new JsonResponse([], 204)
                : redirect()->back();
}

Or You Can Do this in Your Default Login Controller in Line 31

protected $redirectTo = "/your-path";
Related