When I try to authenticate the user with using facebook so I am able to store data into the user table but the failure to create data into the soical_accounts.So after that errors with come up "call to a member funtion create() on null". Can anyone provide me solution that where I am wrong.
In my SocialAccountControll, I have the following method
public function handleProviderCallback($provider)
{
try{
$user = Socialite::driver($provider)->user();
} catch (Exception $e) {
return redirect('/login');
}
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
// redirectTo, so that way we use the same redirect location that the rest of our authentication uses.
//This is a normal protected function that you can add in your users table to redirect a user wherever
// you want to set that redirect to.
//return redirect($this->redirectTo);
return redirect('/home');
}
public function findOrCreateUser($socialUser, $provider)
{
$account = SocialAccount::where('provider_name', $provider)->where('provider_id',$socialUser->getId())->first();
if($account)
{
return $account->user;
}
else
{
$user = User::where('email', $socialUser->getEmail())->first();
if(! $user)
{
$user = User::create([
'email' => $socialUser->getEmail(),
'name' => $socialUser ->getName()
]);
}
$user->accounts()->create([
'provider_name' => $provider,
'provider_id' => $socialUser->getId()
]);
return $user;
}
}
In my database migration, I have users and social_accounts and user have one to many relationship with social_accounts.
user table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Social_accounts table:
public function up()
{
Schema::create('social_accounts', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('user_id');
$table->string('provider_name')->nullable();
$table->string('provider_id')->unique()->nullable();
$table->timestamps();
});
}
User Model class User extends Authenticatable { use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function accounts()
{
$this->hasMany('App\SocialAccount');
}
}
SocialAccount Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class SocialAccount extends Model { protected $fillable = [ 'provider_name', 'provider_id' ];
public function user() {
return $this->belongsTo('App\User');
}
}