Manually setting the intended URL for routes in Laravel
In Laravel, you can use the intended
method on the redirect
response to redirect the user back to the intended URL after they’ve been authenticated. This is usually used when the user is not authenticated and they’re trying to access a protected route.
However, sometimes you might want to manually set the intended URL for a route. For instance, the user is on some page and you want your user to be redirected to a feedback page. Once the user submits the feedback, you want to redirect the user back to the page they were on before they submitted the feedback.
Well, in that case, you can programmatically set the intended URL using the setIntendedUrl
method of the Illuminate\Support\Facades\Redirect
facade.
Disclaimer: I learned this nifty trick in one of Josh Cirre’s videos.
So, take the following for example.
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () {
if (!session('feedback_completed', false)) {
// Save the intended URL and redirect to the feedback form
Redirect::setIntendedUrl('/dashboard');
// Redirect to the feedback form
return redirect('/feedback-form');
}
return "Welcome to the Dashboard!";
});
// Feedback Form (GET + POST)
Route::get('/feedback-form', function () {
return "
<form method='POST' action='/feedback-form'>
" . csrf_field() . "
<label for='feedback'>Your Feedback:</label>
<textarea name='feedback' id='feedback' required></textarea>
<button type='submit'>Submit</button>
</form>
";
});
Route::post('/feedback-form', function () {
// Save feedback completion in session
session(['feedback_completed' => true]);
// Redirect back to the intended URL or fallback to /home
return redirect()->intended('/home');
});
As you can tell, in the above example, we’re setting the intended URL to /dashboard
before redirecting the user to the feedback form. And once the user submits the feedback, we’re redirecting the user back to the intended URL using the intended
method. Or if the intended URL is not set, we’re redirecting the user to /home
.
The best thing is that this can be used even if the user is not logged in since it’s using the session to store the intended URL.
Pretty handy I must say!
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.