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.
Did you try this in your routes.php ?
this will redirect you to default page of your project i.e. start page.
Here is my solution for 5.1. I needed someone to click a "Like" button on a post, get redirected to login, then return to the original page. If they were already logged in, the
href
of the "Like" button was intercepted with JavaScript and turned into an AJAX request.The button is something like
<a href="/like/931">Like This Post!</a>
./like/931
is handled by a LikeController that requires theauth
middleware.In the Authenticate middleware (the
handle()
function), add something like this at the start:Change
/auth/login
to whatever your URL is for logging in. This code saves the original page's URL in the session unless the URL is the login URL. This is required because it appears as though this middleware gets called twice. I am not sure why or if that's true. But if you don't check for that conditional, it will be equal to the correct original page, and then somehow get chanced to/auth/login
. There is probably a more elegant way to do this.Then, in the
LikeController
or whatever controller you have that handles the URL for the button pushed on the original page:This method is super simple, doesn't require overriding any existing functions, and works great. It is possible there is some easier way for Laravel to do this, but I am not sure what it is. Using the
intended()
function doesn't work in my case because the LikeController needed to also know what the previous URL was to redirect back to it. Essentially two levels of redirection backwards.You may use Redirect::intended function. It will redirect the user to the URL they were trying to access before being caught by the authenticaton filter. A fallback URI may be given to this method in case the intended destinaton is not available.
In post login/register:
For Laravle 5.7, You need to make change into:
Change this:
To this:
For laravel 5.* try these.
or