Laravel 5.8 Facebook Socialite Authentication

Ikechukwu Chidera
Mar 17 · 5 min read

Greetings guys…

Here, I’ll be out-listing step by step procedures of successfully integrating Facebook authentication using Socialite in your Laravel blog.

I’ll be making use of images to accurately illustrate and guide you through. All codes needed for the integration are also included here.

Now, let’s get started…

STEP 1: Open your Laravel blog in Terminal(for Linux users) or Git Bash(for Windows users) and run the laravel migration command using:

php artisan migrate

Also, run the laravel authentication command using:

php artisan make:auth

This command will automatically update your route files and set up Login and Registration dashboard on your laravel welcome page.

STEP 2: Next, we download the laravel/socialite package using this command:

composer require laravel/socialite

After this, we need to set up configurations for our Socialite package.

We do this by going to “app.php” inside “config” folder and insert the following codes.

In “app.php”, scroll down to ‘providers’ section and add Socialite service provider using:

Laravel\Socialite\SocialiteServiceProvider::class,

On the same page; “app.php”, also scroll down to ‘aliases’ and add this config:

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

Still on the socialite configurations, switch to “services.php” still inside the “config” folder, add this command:

'facebook' => [
'client_id' => env('FACEBOOK_APP_ID'),
'client_secret' => env('FACEBOOK_APP_SECRET'),
'redirect' => env('FACEBOOK_REDIRECT'),
],

Now we’re done with the configurations, let’s go to step 3…

STEP 3: Here, we create our Facebook app so that we can get a ‘client_id’ and ‘client_secret’ from Facebook.

We do this by going to Facebook’s developers URL: https://developers.facebook.com/ and log in with your Facebook account.

Go to ‘My Apps’, proceed to ‘Add New App’ as shown below…

Next, input your App name and click on ‘Create App Id’ as shown below…

Next, go to Settings -> Basic, copy your app_id and app_secret.

Remember to click on show to view and copy your app_secret. This is illustrated below…

Next, click on the ‘+’ button beside ‘PRODUCTS’, select ‘Facebook Login’, also select ‘WWW’. Then add your website URL: https://localhost:8000 and click on ‘Save’ as shown below…

Then go to Facebook Login -> Settings, scroll down to ‘Valid OAuth Redirect URL’ and add your callback /redirect URL: https://localhost:8000/callback and Save changes as illustrated below…

We’re done with all App settings, now let’s go over to STEP 4.

STEP 4: Now got to your ‘.env’ file and update with these:

FACEBOOK_APP_ID=xxxxxxxxxxxxxxxx
FACEBOOK_APP_SECRET=xxxxxxxxxxxxxxxxxxxxxx
FACEBOOK_REDIRECT=http://localhost:8000/callback

Remember to replace App_id and secret with those received from facebook.

Next, create a controller for laravel Facebook login…

php artisan make:controller SocialAuthFacebookController

In this controller, we’ll add two functions: redirect() function to redirect the user to Facebook and callback() function is used for handle user when callback from Facebook. To achieve this, we add the following codes to our controller:

<?php
namespace App\Http\Controllers;use Illuminate\Http\Request;
use Socialite;
use App\Services\SocialFacebookAccountService;
class SocialAuthFacebookController extends Controller
{
/**
* Create a redirect method to facebook api.
*
* @return void
*/

public function redirect()
{
return Socialite::driver('facebook')->redirect();
}
/**
* Return a callback method from facebook api.
*
* @return callback URL from facebook
*/

public function callback(SocialFacebookAccountService $service)
{
$user = $service->createOrGetUser(Socialite::driver('facebook')->user());
auth()->login($user);
return redirect()->to('/home');
}
}

Next we update our route; routes -> web.php using:

Route::get('/redirect', 'SocialAuthFacebookController@redirect');
Route::get('/callback', 'SocialAuthFacebookController@callback');

STEP 5: Now navigate to ‘resources’ -> ‘views’ -> ‘auth’ -> ‘login.blade.php’. Below the closing tag for <div class=”form-group”>, add the following codes:

<br />
<p style="margin-left:265px">OR</p>
<br />
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<a href="{{url('/redirect')}}" class="btn btn-primary">Login with Facebook</a>
</div>
</div>

These codes will add a button for Facebook login on your laravel login page.

Now let’s create a model and a table for our logged in facebook accounts. we use this command:

php artisan make:model SocialFacebookAccount -m

Now navigate to ‘app’ -> ‘SocialFacebookAccount.php’ and add these codes for our model…

<?php// SocialFacebookAccount.phpnamespace App;use Illuminate\Database\Eloquent\Model;class SocialFacebookAccount extends Model
{
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}

Next navigate to ‘database’ -> ‘migrations’ -> ‘create_social_facebook_accounts_table.php’ and add these codes…

<?php // create_social_facebook_accounts.php use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSocialFacebookAccountsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('social_facebook_accounts', function (Blueprint $table) {
$table->integer('user_id');
$table->string('provider_user_id');
$table->string('provider');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('social_facebook_accounts');
}
}

Also run the following command to refresh our database tables.

php artisan migrate:refresh

STEP 6: Here, we handle our authentication services, through which the users can be registered or login if user already exists.

This is how we do it:

We manually create a folder named ‘Services’ inside ‘app folder’, then create a file named ‘SocialFacebookAccountService.php’. We now add the following codes to our newly created file…

<?phpnamespace App\Services;
use App\SocialFacebookAccount;
use App\User;
use Laravel\Socialite\Contracts\User as ProviderUser;
class SocialFacebookAccountService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialFacebookAccount::whereProvider('facebook')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialFacebookAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook'
]);
$user = User::whereEmail($providerUser->getEmail())->first(); if (!$user) { $user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'password' => md5(rand(1,10000)),
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}

Hurray, we’ve successfully integrated facebook login to our laravel blog.

Now run php artisan serve

and test the authentication process.

I hope the procedures are clear and understandable. Feel free to comment and ask questions where confused.

Want to integrate Google Authentication on your laravel project…? Click here.

Also, don’t forget to give a ‘clap’ for this post. Thank you.