Would you like to offer a Facebook login functionality next to a regular e-mail based login? This is a tutorial to achieve that with Laravel 5 and the Socialite plugin. This tutorial is based on Matt Stauffer’s tutorial.
First of all pull in Laravel Socialite via composer:
composer require laravel/socialite
Create the users and password_remember migration:
$table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('avatar'); $table->string('password', 60); $table->boolean('is_admin'); $table->string('facebook_id'); $table->rememberToken(); $table->timestamps();
Get your Facebook developer id and secret at: https://developers.facebook.com/.
Insert the Facebook credentials into the app/services.php file:
'facebook' => [ 'client_id' => env('FACEBOOK_ID'), 'client_secret' => env('FACEBOOK_SECRET'), 'redirect' => env('FACEBOOK_URL'), ],
In my case, I store them in the .env file as environment variables:
FACEBOOK_ID=xxx FACEBOOK_SECRET=yyy FACEBOOK_URL=http://myapp.devapp/auth/facebook/callback
Create a users model and make sure that some fields are fillable:
So the model and migrations are prepared, if necessary, run your migration:
php artisan migrateRegister a new controller in your routes file (if there's an auth controller already, do it above the auth controller):
Route::get('/auth/facebook', 'Auth\SocialController@redirectToProvider'); Route::get('/auth/facebook/callback', 'Auth\SocialController@handleProviderCallback');Create the Facebook Social Auth Controller (app/Http/Controllers/Auth/SocialController.php):
redirect(); } /** * Obtain the user information from Facebook. * * @return Response */ public function handleProviderCallback() { $user = Socialite::driver('facebook')->user(); $authUser = $this->findOrCreateUser($user); Auth::login($authUser, true); return redirect()->back(); } /** * Return user if exists; create and return if doesn't * * @param $fbUser * @return User */ private function findOrCreateUser($fbUser) { if ($authUser = User::where('facebook_id', $fbUser->id)->first()) { return $authUser; } return User::create([ 'name' => $fbUser->name, 'email' => $fbUser->email, 'facebook_id' => $fbUser->id, 'avatar' => $fbUser->avatar ]); } }You can now link to your social auth controller from somewhere in your blade view:
Login with FacebookImportant safety note
If you'd like to keep the possibility for people to login, make sure that you've empty password validation checks, so that people can't sign in with only Facebook e-mail addresses.
That's it. Do you've additions to this tutorial? Let me know in the comments.