You’ve set up your new Laravel 8 project and installed the
laravel/ui composer package. Moreover, you’ve added the auth boilerplate along with the vue or react preset and migrated the required database tables for your auth system.
You are ready to start building your project’s functionality but would like to set the authentication up in such way, so that your users are redirected back to the page they were before trying to sign in. How would that work?
If you have added the auth middleware to protect specific routes in your
routes/web.php, then your users will be redirected to the login page if they try to access them. In that case, they will be redirected back to the intended page automatically after successful authentication.
Now, let’s say we have a publicly available blog page and we also link to the login form in that page. How can we set up the auth system in such way, so that they are redirected back to our blog page after successful authentication? The solution is easy if we take advantage of the feature already implemented by default.
Laravel uses the
url.intented key to store the url of the intended page in the session, so it automatically knows where to redirect after login. This only works though, when we try to access a protected page and we are automatically redirected to the login.
To make it work even when we just link to the login page, we will have to make few changes to the original code in the following files.
After that change, the users will always be redirected to the url saved in the url.intented session key if it is set.
We will have to add the previous function in the LoginController class which will basically override the default one from the auth preset which just returns the
What it does, is to always store the previous url page in the session if the previous page is from our website but not the login page itself. Now, we can link to the login route from any other page we want and have the auth system redirect users back to the original page after successful login.
That’s all it takes to implement such functionality! I hope that this Laravel tip is helpful. Be sure to stay tuned for more in the future.