Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

on3nx's avatar
Level 1

Redirect to previous page after login

This maybe a very basic question.

I have /privatepage that only authenticated user able to access

questions:

  1. how to redirect to /login, if i'm guest (not authenticated) and i hit /privatepage
  2. once i'm successfully login from /login, how to redirect to the previous page (/privatepage)
  3. similar like no.2 - in /login page, if i come from /aboutpage (which a public page) - after login successfull, how do i redirect back to /aboutpage (or the previous page)?

i read redirect()->intended() function but i'm still dont understand fully.

ok, let's put it this way,

if i have: privatepage controller:

class PrivateController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); }

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return view('private');
}

}

when i hit private page as guest, it will redirect me to login page but after i login, it will redirect me to home page (the page that come in standard laravel package)

how to redirect to privatepage after i login?

Thank you

0 likes
16 replies
SaeedPrez's avatar

What you want is default Laravel authentication behavior..

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());

If a user visits /privatepage and that page is protected by the auth middleware then the user is redirected to the login page and /privatepage is saved to session as url.intended. Then after a successful authentication Laravel checks if the session has the url.intended key, and if does, it will redirect to the URL saved in the session. If not, it will redirect to whatever page you have defined, default is /home.

If you would like to manually handle what happens when a user is authenticated, then you can create a function called authenticated() which will be called instead.

GitHub

1 like
on3nx's avatar
Level 1

Thank you for the reply @SaeedPrez

Where should i put: return $this->authenticated($request, $this->guard()->user()) ?: redirect()->intended($

In my case above?

SaeedPrez's avatar

@on3nx that is default Laravel behavior, take a look at the GitHub link I provided.

on3nx's avatar
Level 1

@SaeedPrez you right! thanks for the help, it's default laravel behavior. then i'm wondering, if i like to change this default behavior, how i do this? e.g. everytime i login go to /about page and when i suppose to use intended(); ?

SaeedPrez's avatar

@on3nx you make me repeat myself, did you read my first reply? :(

If you would like to manually handle what happens when a user is authenticated, then you can create a function called authenticated() which will be called instead.

on3nx's avatar
Level 1

@SaeedPrez I'm sorry i think i missed that.

ok, and yes i just realize if the page is not protected by the auth middleware, after login (i have login form in every page in header.blade) it will always redirect to /home - which i dont want this... it should redirect page to where the user left before.

so I assume i should create authenticated() method in my controller, am i right? - let me try this and see if it's works

thanks for your kind help!

on3nx's avatar
Level 1

Ok, i solve that with this: $this->redirectTo = URL::previous(); - in my login controller:

i'm not sure if there any issue with my approach here:

use AuthenticatesUsers;

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/home';

protected $loginPath = '/login';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->redirectTo = URL::previous();
    $this->middleware('guest', ['except' => 'logout']);
}

}

1 like
Laraveldeep's avatar

@on3nx :

What version are you using?

I tried your solution but not working for me.

In my case 'login' is not required but certain things are visible or invisible depending upon authentication status. I am looking for a same solution

I am using 5.3

use Illuminate\Support\Facades\URL;
.
.
.
protected $redirectTo = '/';

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

Didn't work for me. It goes to my home page regardless.

I have tried to check

dd($this->redirectTo);

Its producing the correct result as expected but redirection to previous page is not working.

I must have missed something.

on3nx's avatar
Level 1

@Laraveldeep I'm using 5.3 i'm sorry, but not really sure for your case, so far it works fine on me.

diguin's avatar

@Laraveldeep

It doesn't work for me neither, but i found another option that maybe works for you.

In loginController add:

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

It will overwrite the showLoginForm() and 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 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.

Hope it helps.

4 likes
ha_ko2008's avatar

do whatever you do, your problem is that the previous URL is the login page, so even you solve the previous URL handling, so you will get back to the login page and sense you are logged in automatically you will be redirected to the '/' URL (see the file app\Http\Middleware\RedirectIfAuthenticated.php Line°: 21 `if (Auth::guard($guard)->check()) { return redirect('/'); )

i have solved it by saving session value and recall it like this :

1- Go to login blade page (resources\views\auth\login.blade.php) put this code in :

<?php
                        
  Session::set('backUrl', URL::previous());
?>

2- Then go to (this for logout action)(vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php) lock look for function logout and change its return to redirect()->back()


<?php
                        
  public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect()->back();
    }
?>

3- After that go to (vendor\laravel\framework\src\Illuminate\Foundation\Auth\RedirectsUsers.php) first you should use Session; just change the redirectPath function its return


return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';

to


public function redirectPath()
    {

        
        return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
        
    }


i didn't say it's the perfect solution but after a long way looking, i just invented it

1 like
sohail123's avatar

@ha_ko2008 thanks. for me I have to change method name

  public function redirectTo()
    {
        return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
    }
1 like
benmag's avatar

I know this was asked a long time ago but this is the solution I came up with. I think it's pretty simple and clean, thought it might be helpful to others.

Create a middleware ReturnAfterAuthentication

public function handle($request, Closure $next)
{
    $request->session()->put('url.intended', $request->url());
    return $next($request);
}

Then register ReturnAfterAuthentication in Kernel.php

Now if you want to have a public page that the user gets redirected back to after logging in, you can just apply the middleware to the route

Route::get('aboutus', function(\Illuminate\Http\Request $request) {
    return view('aboutus');
})->middleware('returnAfterAuth');
sebastian.bouckaert@sbsoftware.be's avatar

Probably to late but... cleanest solution I found was I placed this is my AuthenticatesUsers:

public function showLoginForm() { Session::put('backUrl', URL::previous());

    return view('auth.login');
}

and this in my LoginController

protected $redirectTo = '/home';

protected function redirectTo()
{
   
        $this->redirectTo = Session::get('backUrl'); // this value is added to the 
    

    return $this->redirectTo;
}

So it basically save the url from where you came from before the login page. When you are logged in it hets the value from the sessions.

i7sn's avatar

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'));
}
3 likes

Please or to participate in this conversation.