42

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.

Marged
  • 10,577
  • 10
  • 57
  • 99
cs1h
  • 475
  • 1
  • 5
  • 8
  • 1
    Even though the answer here alludes to Laravel 4, I'm sure it'll still work in 5. http://stackoverflow.com/questions/15389833/laravel-redirect-back-to-original-destination-after-login – Danny Kopping Apr 29 '15 at 21:22
  • Hmm Laravel 4 and 3 did not roll with the authenticatable contracts that laravel 5 does, I don't think those will be relevant. – Matthew Brown Apr 29 '15 at 21:26
  • [Here](https://stackoverflow.com/questions/15389833/laravel-redirect-back-to-original-destination-after-login) is similar problem solved very nice. – Peter Šeliga Mar 14 '18 at 20:29
  • Solution For Laravel 5.5, following link https://stackoverflow.com/a/47487117/8595764 – Hasan AbdulRahim Oct 24 '18 at 16:48

15 Answers15

55

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.

Diguin
  • 835
  • 8
  • 17
36

For Laravel 5.5, following code worked for me by just updating LoginController.php

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


protected function authenticated(Request $request, $user)
{
    return redirect(session('link'));
}
19

Please use redirect()->intended() instead in Laravel 5.1

You can also see more about it here: http://laravel.com/docs/5.1/authentication

Marged
  • 10,577
  • 10
  • 57
  • 99
bnqtoan
  • 779
  • 1
  • 7
  • 14
  • This worked for me by also setting `url.intended` in the session where I redirected to login: Session::put('url.intended', \URL::full()); – antoineMoPa Dec 14 '17 at 14:41
  • @bnqtoan Maybe you can help me. Look at this ; https://stackoverflow.com/questions/49373967/how-can-i-redirect-back-to-previous-page-after-login-on-vue-and-laravel – moses toh Mar 20 '18 at 02:46
  • Better answer here! I used this code : return redirect()->intended(route('user.dashboard')); and it works well. – CDO Oct 19 '18 at 08:21
  • But before that, Laravel shows a 403 error page without any action. Instead, how to redirect automatically to the login page, and then to the intended page?? – Pathros Aug 23 '20 at 04:25
17

For Laravel 5.3

inside App/Http/Controllers/Auth/LoginController add this line to the __construct() function

$this->redirectTo = url()->previous();

So the full code will be

public function __construct()
{
    $this->redirectTo = url()->previous();
    $this->middleware('guest', ['except' => 'logout']);
}

It works like a charm for me i'm using laravel 5.3.30

  • 1
    Thank for the answer, which works nicely -- but in order for this to happen, it seems you have to 'include' the login form in the page you want to be redirected back to. Logging in by going to `your.app/login` will only redirect you back to the `'/home'` page. – hktang Jun 02 '17 at 07:06
  • Working like a charm with Laravel 5.5 – Onix Oct 13 '17 at 12:50
  • This does not work after authentication error on login. It redirects to login form after successful login. – James Mar 14 '18 at 17:12
10

For Laravel 5.4, following code worked for me by just updating LoginController.php

use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;


public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
    Session::put('backUrl', URL::previous());
}


public function redirectTo()
{
    return Session::get('backUrl') ? Session::get('backUrl') :   $this->redirectTo;
}
VipinKundal
  • 442
  • 6
  • 14
8

The Laravel 5.6, When user insert wrong credentials then login page will reload and session(['link' => url()->previous()]); will take login URL in link variable. So the user will redirect to a login page again or redirect to /home if login success. So to avoid these below code working for me! After that no matter how much time user insert wrong credentials he will redirect after login to exactly where he was before login page.

Update or overwrite public function showLoginForm() in LoginController.

public function showLoginForm()
{
    if (session('link')) {
        $myPath     = session('link');
        $loginPath  = url('/login');
        $previous   = url()->previous();

        if ($previous = $loginPath) {
            session(['link' => $myPath]);
        }
        else{
            session(['link' => $previous]);
        }
    }
    else{
         session(['link' => url()->previous()]);
    }

    return view('auth.login');
}

Also, Update or Overwrite protected function authenticated(Request $request, $user) in LoginController.

protected function authenticated(Request $request, $user)
{     
    return redirect(session('link'));      
}
ImZedi
  • 294
  • 4
  • 15
8

If you want to redirect always to /home except for those pages with comments, then you should overwrite your redirectTo method in your LoginController:

public function redirectTo()
{
     return session('url.intended') ?? $this->redirectTo;
}

On all pages where you want to remain on the site, you should store the url for one request in the session:

public function show(Category $category, Project $project){
   // ...

   session()->flash('url.intended' , '/' . request()->path());
}
Adam
  • 25,960
  • 22
  • 158
  • 247
6

Look into laravel cheat sheet

and use:

URL::previous();

to go to the previous page.

Loko
  • 6,539
  • 14
  • 50
  • 78
  • Maybe you can help me. Look at this ; https://stackoverflow.com/questions/49373967/how-can-i-redirect-back-to-previous-page-after-login-on-vue-and-laravel – moses toh Mar 20 '18 at 02:46
  • @Muthusamy Thanks for the notice. I updated the link. – Loko Jan 07 '19 at 08:27
6

Redirect to login with the current's page url as a query string:

<a href="{{ url('login?redirect_to=' . urlencode(request()->url())) }}">login</a>

In your LoginController check if exists and save the query string in session then redirect to the url after login

public function __construct() {
        parent::__construct();
        if ( \request()->get( 'redirect_to' ) ) {
            session()->put( 'redirect.url', \request()->get( 'redirect_to' ) );
        }
        $this->middleware( 'guest' )->except( 'logout' );
}

protected function authenticated(Request $request, $user) {
        if(session()->has('redirect.url') {
             return redirect( session()->get( 'redirect.url' ) );
        }
}
George Tudor
  • 136
  • 2
  • 4
2

Laravel 5

(maybe 6 also, not tested, if someone knows it please update the answer)

add this to LoginController:

protected function redirectTo(){
    return url()->previous();
}

Note: if present the field $redirectTo , remove it

Luca C.
  • 11,714
  • 1
  • 86
  • 77
  • 1
    You don't need to remove it. The function redirectTo() takes precedence over variable $redirectTo, so might equally be a fall back especially when the first page user access is the login page – DAVID AJAYI Mar 27 '20 at 11:28
0

in your RedirectIfAuthenticated.php change this code

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect()->intended('/contactus');
        }

        return $next($request);
    }

please notice to :

return redirect()->intended('/contactus');
Mahdi Abedi
  • 124
  • 2
  • 3
0

Inside your template file you can just use:

{{ url()->previous() }}

To redirect from the controller you should use

return redirect()->back(); 

or Just

return back();
Rakesh kumar Oad
  • 1,332
  • 1
  • 15
  • 24
0
use Illuminate\Support\Facades\Redirect;

public function Show_Login_Form()
{   
    $back = Session::put('url_back',url()->previous());
    $current = url()->current();
    
    if(Session::get('user_id'))
    {
        if ($back == $current) { // don't back Login Form
            return Redirect::to('home');
        }
        elseif (Session::has('url_back')) {
            return Redirect::to('home');
        }
        else{
            return redirect()->back();
        }
    }
    else{
        if ($back == $current) {
            return Redirect::to('home');
        }
        else{
            Session::put('url_back',url()->previous());
        }
        return view('account.customer-account.login');
    }
}

public function signin_user(Request $request) // Login post
{
    $username = $request->input_username_login;
    $password = md5($request->input_password_login);

    $result = DB::table('tbl_user')
              ->where([['user_email',$username],['user_password',$password]])
              ->orWhere([['user_phone',$username],['user_password',$password]])
              ->first();

    if($result){

        Session::put('user_id', $result->user_id );
        Session::put('user_name', $result->user_name);
        Session::put('user_username', $result->user_username);
        Session::put('user_avatar', $result->user_avatar);     
        
        return Redirect::to(Session::get('url_back')); // Back page after login
    } else {
        Session::put('message_box', 'Error !!!');
        return redirect()->back();
    }
}
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 18 '22 at 16:28
-1

You can use redirect back with Laravel 5:

<?php namespace App\Http\Controllers;

use Redirect;   
class SomeController extends Controller { 
    public function some_method() {
       return Redirect::back()
    }
}
mirza
  • 5,685
  • 10
  • 43
  • 73
-2

Use Thss

return Redirect::back('back-url')

Gowthaman D
  • 574
  • 7
  • 19