I have a laravel app version 8.83.23. I have multiple views that have links to show the login page. A simple example is this:
Think of a blog post. "you must login to post a comment".. The user clicks "login" and is taken to the login view (auth.login). The user fills the form and submits. The user is authenticated. I then want the authenticated user to be redirected to the page where they originally clicked login.
Is there a simple solution such as changing $redirectTo in the LoginController.php to something dynamic?
CodePudding user response:
The way I am usually using it is with the Laravel intended
method.
The
intended
method provided by Laravel's redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.
We are setting the url.intended
value in the current session so when the user visits the login page, it will check for the url.intended
to redirect the user where they were when they clicked the login URL. If there is no url.intended
it will just redirect to the default RouteServiceProvider::HOME
.
The AuthenticatedSessionController.php store method is the one that came with the Inertia scaffolding in Laravel 8.83.1 ( not sure if that changed since )
MyController.php
class QuotesController extends Controller
{
public function productQuote(string $product)
{
if (auth()->guest()) {
session()->put('url.intended', request()->fullUrl());
}
return view(
'get-product-quote',
['product' => $this->getProduct($product), 'user' => $this->getUser()]
);
}
}
And in the get-product-quote
view I simply do this:
<x-app-layout>
<div >
@guest
<div>
<a :href="route('login')" >Log in for faster quote submitting process</a>
</div>
@endguest
@auth
...
<p>do the authenticated user stuff</p>
@endauth
</div>
</x-app-layout>
AuthenticatedSessionController.php
class AuthenticatedSessionController extends Controller
{
/**
* Handle an incoming authentication request.
*
* @param \App\Http\Requests\Auth\LoginRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::HOME);
}
}
CodePudding user response:
If you want to redirect back to the page where the user logged in
return back();