php artisan make:model SocialProfile -m
Lo primero en el migrate de user poner nullable el password:
$table->string('password')->nullable();
En el nuevo migration de SocialProfile creado añadir:
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('social_id')->unique();
$table->string('social_name');
$table->string('social_avatar');
Pasar el migrate para generar de nuevo todas las tablas:
php artisan migrate:fresh
En el modelo User:
use App\SocialProfile;
...
public function socialProfiles() { // es profiles pq un user puede tener varios (facebook, google, twitter, etc)
return $this->hasMany(SocialProfile::class);
}
En el modelo SocialProfile:
use App\User;
...
protected $fillable = ['user_id', 'social_id', 'social_name', 'social_avatar'];
...
public function user() {
$this->belongsTo(User::class);
}
En SocialAuthController.php:
public function callbackFacebook(Request $request) {
if ($request->get('error')) { // por ejemplo al dar a cancelar cuando se loguea con facebook
return redirect()->route('login');
}
$userSocialite = Socialite::driver('facebook')->user();
// check si ese email está ya dado de alta
$user = User::where('email', $userSocialite->getEmail())->first();
if (!$user) {
$user = User::create([
'name' => $userSocialite->getName(),
'email' => $userSocialite->getEmail(),
]);
}
// check que ese social_id ya no esté metido de antes
$socialProfile = SocialProfile::where('social_id',$userSocialite->getId())
->where('social_name', 'Facebook')->first();
if (!$socialProfile) {
$socialProfile = SocialProfile::create([
'user_id' => $user->id,
'social_id' => $userSocialite->getId(),
'social_name' => 'Facebook',
'social_avatar' => $userSocialite->getAvatar(),
]); }
// una vez metido o no metido (por estar de antes) vamos a loguearlo
auth()->login($user);
return redirect()->route('home');
}
No hay comentarios:
Publicar un comentario