Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - After login redirect back to previous page

Tags:

php

laravel-5

I have a page with a some content on it and a comments section. Comments can only be left by users who are signed in so I have added a login form to the page for users to sign in with (this only shows if they are not already logged in).

The problem I have is that when the user signs in they get redirected back to the home page and not the page they were previously on.

I have not changed the login method from the out of the box set-up.

Can anyone suggest a simple way to set the redirect url. My thoughts are that it would be good to be able to set it in the form.

like image 439
cs1h Avatar asked Apr 29 '15 21:04

cs1h


People also ask

How do I redirect a previous URL after login?

The most common ways to implement redirection logic after login are: using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL.

How do I redirect back to original URL after successful login in laravel?

You can apply this filter to the routes that need authentication. Route::filter('auth', function() { if (Auth::guest()) { return Redirect::guest('login'); } }); 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. return Redirect::intended();

How do I go back to previous page in laravel?

Redirecting users to the previous page or url in laravel is very easy. You have to use url()->previous() method on Redirect Fasade. url()->previous() method gives you the last visited page url and Redirect Fasade return you to that page.


1 Answers

Solution for laravel 5.3:

In loginController overwrite the showLoginForm() function as this one:

public function showLoginForm() {     if(!session()->has('url.intended'))     {         session(['url.intended' => url()->previous()]);     }     return view('auth.login');     } 

It will set the "url.intended" session variable, that is the one that laravel uses to look for the page which you want to be redirected after the login, with the previous url.

It also checks if the variable has been set, in order to avoid the variable to be set with the login url if the user submit the form with an error.

like image 187
Diguin Avatar answered Oct 03 '22 00:10

Diguin