Search code examples
phplaravelfacebooklaravel-socialite

Laravel with facebook login


I am having troubles in logging in with Facebook.

I am using Laravel Socialite, I have followed all the instructions but I am having problems at method callback.

This is what i do :

public function redirectToFacebook()
{
    return Socialite::driver('facebook')->redirect();
}
public function handleFacebookCallback()
{
    $userSocial = Socialite::driver('facebook')->user();
    //return $userSocial;
    $finduser = User::where('facebook_id', $userSocial->id)->first();
    if($finduser){
        Auth::login($finduser);
        return Redirect::to('/');
    }else{
        $new_user = User::create([
           'name'        => $userSocial->name,
           'email'       => $userSocial->email,
           'image'       => $userSocial->avatar_original,
           'facebook_id' => $userSocial->id
        ]);
        Auth::login($new_user);
        return redirect()->back();
    }
}

SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value

How to get the password of facebook?


Solution

  • When using Socialite you don't need the password of Facebook or any other service, because you will receive a token from the platform that you can use instead of a username / password.

    The problem here is that you are trying to create a user without supplying a password, while the password field is not nullable in the users table.

    You can solve this for example by creating a migration that changes the password column and makes it nullable, i.e.:

    Schema::table('users', function (Blueprint $table) {
        $table->string('password')->nullable()->change();
    });
    

    Still, you have to decide if this is the authorization setup you want and if you want users in your database without a password.