Support the ongoing development of Laravel.io →
Authentication Session

Hi people, im trying, with the default Laravel authentication functionallity, to redirect the user to his previous page after login, dynamically. An example:

1- The user is in example.com/posts 2- The user goes to example.com/login an then logins 3- After login, redirect the user back to example.com/posts

So, the redirect URL is variable. The file App/Http/Controllers/Auth/Authcontroller.php has a protected $redirectTo property, but i dont want to use the same URL always.

This is my actual method, but it changes core laravel files, and that is problematic:

1- Coment the redirectTo property in App/Http/Controllers/Auth/Authcontroller.php :

// protected $redirectTo = '/';

2- Inside vendor/laravel/framework/src/illuminate/Foundation/auth/AuthenticatesUsers.php i get the previous URL and put it in the session:

$request->session()->put('pre-url', URL::previous()); 

3- Finally, in illuminate/foundation/auth/redirectsusers.php, i change:

return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';

for:

return property_exists($this, 'redirectTo') ? $this->redirectTo : session('pre-url');

It works, but i need to change two core files. Is there a better way to do it? Thanks to all.

Last updated 3 years ago.
0

Redirect them to login using redirect()->guest('login'). It will store an intended URL in the session and should redirect there after login.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

sebasspf sebasspf Joined 22 Dec 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.