This seems like a pretty basic flow, and Laravel
has so many nice solutions for basic things, I feel like I'm missing something.
A user clicks a link that requires authentication. Laravel's auth filter kicks in and routes them to a login page. User logs in, then goes to the original page they were trying to get to before the 'auth' filter kicked in.
Is there a good way to know what page they were trying to get to originally? Since Laravel is the one intercepting the request, I didn't know if it keeps track somewhere for easy routing after the user logs in.
If not, I'd be curious to hear how some of you have implemented this manually.
Laravel >= 5.3
The Auth changes in 5.3 make implementation of this a little easier, and slightly different than 5.2 since the Auth Middleware has been moved to the service container.
Modify the new Middleware auth redirector
Change the handle function slightly, so it looks like:
TL;DR explanation
The only difference is in the 4th line; by default it looks like this:
Since Laravel >= 5.3 automatically saves the last "intended" route when checking the Auth Guard, it changes to:
That tells Laravel to redirect to the last intended page before login, otherwise go to "/home" or wherever you'd like to send them by default.
Hope this helps someone else - there's not much out there on the differences between 5.2 and 5.3, and in this area in particular there are quite a few.
For Laravel 5.5 and probably 5.4
In App\Http\Middleware\RedirectIfAuthenticated change
redirect('/home')
toredirect()->intended('/home')
in the handle function:in App\Http\Controllers\Auth\LoginController create the
showLoginForm()
function as follows:This way if there was an intent for another page it will redirect there otherwise it will redirect home.
Larvel 5.3 this actually worked for me by just updating LoginController.php
ref: https://laracasts.com/discuss/channels/laravel/redirect-to-previous-page-after-login
I found those two great methods that might be extremely helpful to you.
You can apply this filter to the routes that need authentication.
What this method basically does it's to store the page you were trying to visit and it is redirects you to the login page.
When the user is authenticated you can call
and it's redirects you to the page you were trying to reach at first.
It's a great way to do it although I usually use the below method.
You can check this awesome blog.
For Laravel 5.2 (previous versions I did not use)
Paste the code into the file app\Http\Controllers\Auth\AurhController.php
And import namespace:
use Session;
If you have not made any changes to the file app\Http\Controllers\Auth\AurhController.php, you can just replace it with the file from the GitHub