Search code examples
phplaravellaravel-5.3

laravel 5.3 login with facebook


I am implementing login with facebook in my laravel 5.3 project. It seems to work as I get all the data recorded to the database from a facebook user, but my project sees my auth state as not logged. Also it does not redirect me to the dashboard, but displays a white page with the callback link. Why?

It redirects a user to the fagebook page to login

public function redirectToProvider()
{
    return Socialite::driver('facebook')->redirect();
}

Callback Handler

public function handleProviderCallback()
{
    try{
        $socialUser = Socialite::driver('facebook')->user();
    }
    catch(\Exception $e) {
        return redirect('/dashboard');
    }

    $user = User::where('facebook_id', $socialUser->getId())->first();
    if(!$user){
        User::create([
            'facebook_id' => $socialUser->getId(),
            'name' => $socialUser->getName(),
            'email' => $socialUser->getEmail(),
        ]);

        auth()->login($user);
        return redirect()->to('/dashboard');
    }
}

My auth()->login seems not to work, and redirect also. What may be the problem? Thank you!

routes:

Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'PageController@getDashboard']);

Route::get('auth/facebook', 'Auth\RegisterController@redirectToProvider');
Route::get('auth/facebook/callback', 'Auth\RegisterController@handleProviderCallback');

Solution

  • The behaviour seems correct for the way you have coded the callback handler. I believe what you want to happen is if the user exists then you want to log them in, your current code doe's nothing if the user exists so you need to make sure if the user exists that they are logged in.

    I would change the code as follows:

    $user = User::where('facebook_id', $socialUser->getId())->first();
    
    if(!$user){
        User::create([
            'facebook_id' => $socialUser->getId(),
            'name' => $socialUser->getName(),
            'email' => $socialUser->getEmail(),
        ]);       
    }
    
    if(Auth::loginUsingId($user->id)){
        return redirect()->intended('/dashboard');
    }
    

    This way if there is a user they will still be logged in rather than the handler doing nothing