I got a Laravel project (v5.3) which needs a login with a custom form and with facebook connect.
So, I use Socialite and it's what I need, however, when I login for first time, the callback doesn't redirect to the view/url that I indicate, instead Laravel shows me the next Exception:
ErrorException in SessionGuard.php line 439: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /var/www/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 294 and defined
This is the code in my custom controller :
public function handleProviderCallback()
{
try
{
$socialUser = Socialite::driver('facebook')->user();
}catch(\Exception $e)
{
return redirect('/');
}
$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('/home');
}
So, I check my database and the record is there - Ok ...but I'm not in session - wrong ... if I login with facebook again (keeping the record in the database) I login successfully and the error is gone... Ok but at all...
If I do:
dd($user)
I got a null value the first time In the following times I got nothing...the $user var show in blank...
So I think is this line:
auth()->login($user);
And I tried
\Auth::login($user);
but it doesn't work too...
So, what's could be wrong, any configuration in my project? This example I saw it in tutoriales with Laravel 5.3 so I don't understand what's going on :(
Thank you! And sorry for my english! :)
Do this:
if(!$user)
$user = User::create([
'facebook_id' => $socialUser->getId(),
'name' => $socialUser->getName(),
'email' => $socialUser->getEmail(),
]);
I added $user =
to your existing code. Because when you do Model::create
it returns an object of type Model
.