Wonka
Wonka

Reputation: 8684

Laravel - Redirect::intended route not working

I have a laravel built blog, and to comment on a post (if you're logged out) you must login. I put a link like this:

<a href="{{ URL::route('login') }}">login</a> to do this.

This redirects to the login form, which once filled out and user is authenticated, I have this:

return Redirect::intended('/');

Which takes the user to the homepage, not the page they intended to be on, in this case, the page with the post that they clicked the login link from to be able to comment. How can I return them back to the intended url in this case?

Upvotes: 3

Views: 4625

Answers (2)

aleemb
aleemb

Reputation: 32105

Redirect::intended requires two parts to work. The first is when the user tries to access a restricted page /orders but they aren't logged in you redirect them to the login page via:

redirect()->guest('/login');

Then on your login post-back if authentication is successful you call:

redirect()->intended('/dashboard');

Upvotes: 3

The Alpha
The Alpha

Reputation: 146269

Actually, Redirect::intended('/') works if there is a key available in the session as url.intended otherwise it redirects to the default URL which is in your case '/', so definitely you didn't put the URL in the session. To accomplish this, you may put the URL in the session using something like this:

Session::put('url.intended', 'url...');

So, probably, in the login link, you may add a query string like this:

<a href="{{ URL::route('login') }}?intended=1">login</a>

So, you can track the redirect and in that route's method (before return View) just put the previous URL in the session, using something like this:

if(Input::get('intended')) {
    Session::put('url.intended', URL::previous());
}

Then before you redirect from there, you should remove the URL from the session using something like this:

$intendedUrl = Session::get('url.intended', url('/'));
Session::forget('url.intended');
return Redirect::to($intendedUrl);

This should solve the issue. Also, you may check this answer, could be helpful.

Upvotes: 6

Related Questions