Redirect to Previous URL After Logging in, Laravel v5.5
An end-user visit the website tries to view several products, services by navigating to different pages. If he finally wants to submit an order. Now the website, of course, takes him to login or register page to provide his personal information for shipping or billing purpose. After logging in, he might want the website to take him back again to the previous page where he was viewing the product information.
I was talking about the user experience while browsing the pages, the behavior for the end-user might differ to each other, but the website owner should make a policy for the better user experience. Especially, the e-commerce websites should consider this types of UI for their end-user.
Let's say you are running an e-commerce website, where people can view products, create orders. Let's assume you want the website easily navigates back the user to the previous page after logging into the website.
Let's start building the feature for redirecting the user back to the previous page.
Let's add a section in the login file.
resources/views/auth/login.blade.php
<div class="form-group">
@if (Request::has('previous'))
<input type="hidden" name="previous" value="{{ Request::get('previous') }}">
@else
<input type="hidden" name="previous" value="{{ URL::previous() }}">
@endif
</div>
View the login.blade.php file on github for the full updated code.
Additionally, you might want to add a login link to your website pages like:
<a href="{{ route('login') . '?previous=' . Request::fullUrl() }}">
Login
</a>
When a user clicks the login link, the page redirects to the login page, it then sets the previous
URL to input that will be sent to login POST
request.
/**
* @return string
*/
public function redirectTo()
{
if ($this->request->has('previous')) {
$this->redirectTo = $this->request->get('previous');
}
return $this->redirectTo ?? '/home';
}
The LoginController.php will handle the previous input value to check if there is the previous link to redirect back. A method redirectTo()
created in LoginController.php is responsible to determine the next redirect path after the user is successfully authenticated.
If you're not familiar with Laravel's auth system and confused that only defining the new redirectTo()
method helps in redirecting to our intended URL, then you can have a look at, AuthenticatesUsers.php
, RedirectsUsers.php
. We cannot touch the core files shipped with Laravel framework, but there is a way we can override those methods to change the behavior as per our requirement.
Conclusion
Thanks for reading this article up to the end. If you have any feedback or the article was really useful to you please leave your comments below. Feel free to share with friends if you like it.
Happy Coding!