1

In my Laravel app I have a private page which can be only accessed by Auth users. I am also using social logins, so when a user goes to private page without logging in, Laravel sends user to login page and after successful login, the user is sent back to original destination (private page). Only when a user logs in via Laravel inbuilt Auth system, but when a user logs in via the Social Login method, the user will be directed to the homepage.

This is my Social Login handler after login:

public function handleProviderCallback($provider)
{

    $user = Socialite::driver($provider)->user();

    $authUser = $this->findOrCreateUser($user, $provider);
    Auth::login($authUser, true);
    return redirect('/home');
}

How can I send the user to the original destination if it's present in session, otherwise send them back to home.

Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45
Sunil Meena
  • 481
  • 3
  • 10
  • 19

2 Answers2

4

The documentation mentions it very briefly, but Laravel has a built-in method:

return redirect()->intended('/home')

Whenever the Auth middleware redirects a user because he is not logged in, his original url will be stored. intended checks whether or not that url is stored and uses that, or the fallback you supply as argument.

Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45
4

Use,

return redirect()->intended('/home')

The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.

Saad Suri
  • 1,352
  • 1
  • 14
  • 26