Facebook Login with Socialite Package in Laravel 8 - Step by step guide ?

Laravel

The socialite package helps to make direct login using Facebook possible in a Laravel Project.
Generally, social networks provides secret key and secret token for user authentication for any website.
Basically Laravel provides a simple, convenient way to authenticate with OAuth providers using Laravel Socialite. Socialite currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub and Bitbucket.
Here at Fixwebnode, as part of our Web Development Services, we regularly help our Customers to perform related Laravel Application queries.
In this context, we shall look into how to Integrate, use and implement Facebook socialite login in Laravel 8 application.

1. Install Laravel 8

To begin, we need to install a laravel application running the below command in terminal:
$ composer create-project --prefer-dist laravel/laravel laravel-facebook
This command will install the new setup of Laravel 8 inside a folder named laravel-facebook.

2. Create and Configure Database

Here, We will use MySQL command line for the database management.
To access the MySQL shell type the following command and enter your MySQL root user password when prompted:
$ mysql -u root -p
If you haven't set a password for your MySQL root user, you can omit the -p option.
So, to create the database "laravel_facebook", simply run the below command:
CREATE DATABASE laravel_facebook;
After creating the database, let’s connect it with the Laravel 8 application by setting the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_facebook
DB_USERNAME=root
DB_PASSWORD=root

3. Install UI Authentication in Laravel 8

To manage the login and session for the logged user, we will have to create a login system.
Here, we will be installing the UI Auth package. To install ui/auth package, simply run the below command:
$ composer require laravel/ui

4. Install Auth Scaffolding

Here, we will install auth scaffolding for this UI Auth package. So, here, we will use vue auth. You can use bootstrap auth also. So to run auth scaffolding, run the below command:
$ php artisan ui vue --auth
After running the auth scaffolding, it will ask to install npm. So to install npm, run the below command:
$ npm install && npm run dev
After installing the npm, it will build the CSS and JS file.
After the build of the UI auth, you will be able to see the Login and Register options in the homepage.

5. Install Laravel Socialite Package

To manage social login there is a package called socialite. This package is very helpful for managing social login in Laravel application. Hence, we will be installing this package using below command:
$ composer require laravel/socialite

6. Add Provider and Alias for Socialite Package

After installing the package, we will have to add the provider and alias for this one. So, for adding the provider, you will have to go inside the config/app.php file. You will see the providers array. So, put the below service provider there. After the providers section, you will find the aliases array. Next, you will have to create one alias for this.
In the app.php file, add the below Provider and Alias:
'providers' => [
...
...
...
Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
...
...
...
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

7. Create and Configure App in Facebook

  • Start by creating an app in facebook developer accounts https://developers.facebook.com/. Once logged in, you can see an option of My Apps in the right corner.

  • Now, go to My Apps section, and create a new app there.

  • Then choose the app type. Here, we are going to create Facebook Login, so, you have to opt Consumer in the app type.

  • Now, you have to put the App name, contact details. So, just fill out the details and proceed to Create App.

  • After creating the app, you will have the App. Go to the Settings->basic and copy the App ID and secret.



8. Add Facebook Login Service in Laravel 8

In the project, open the config/services.php file and put the array as showing below. Here, we are creating Facebook login functionality, so we will define the facebook array and inside the facebook array, we will put client id, secret and the callback URL:
return [

...
...
...

'facebook' => [
'client_id' => 'FACEBOOK_APP_CLIENT_ID',
'client_secret' => 'FACEBOOK_APP_CLIENT_SECRET',
'redirect' => 'CALLBACK_RETURN_URL',
],
After putting the service, we will create a column in users_migration table. In the redirect, you have to set the callback return URL on which the response will be coming after the login.

9. Create Column in Users Migration Table

Here, to manage the login authentication using Facebook, we will store the facebook user id in the users table. In order to do that, we will add a column in the users table.
To add column in users table migration, run the below command:
$ php artisan make:migration add_fb_id_column_in_users_table --table=users
This command will create a new migration for the users table.
Now, after creating the migration file, just add a column (timestamp_add_fb_column_in_users_table.php) as shown below:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddFbIdColumnInUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('fb_id')->nullable();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('fb_id');
});
}
}

Once, you have added the column, just migrate the tables with the below command:
$ php artisan migrate
After the successful migration, you will be able to see a new column in the users table.

10. Add Fillable Data in Users Model

After the migration, you will have to set the fillable data in the Users model. Here, We have added the fillable fields.
In the User.php file, set the fillable data:
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
use HasFactory, Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'fb_id'
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

11. Create Controller

To manage the Facebook login authentication, we will create a controller (SocialAuthController):
$ php artisan make:controller SocialAuthController
After creating the controller (SocialAuthController.php
), just put the below snippet there:
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Validator;
use Socialite;
use Exception;
use Auth;

class SocialAuthController extends Controller
{
/**
* Redirect to facebook login
*
* @return void
*/
public function facebookRedirect()
{
return Socialite::driver('facebook')->redirect();
}

/**
* Facebook login authentication
*
* @return void
*/
public function loginWithFacebook()
{
try {

$facebookUser = Socialite::driver('facebook')->user();
$user = User::where('fb_id', $facebookUser->id)->first();
if($user){
Auth::login($user);
return redirect('/home');
}

else{
$createUser = User::create([
'name' => $facebookUser->name,
'email' => $facebookUser->email,
'fb_id' => $facebookUser->id,
'password' => encrypt('test@123')
]);

Auth::login($createUser);
return redirect('/home');
}

} catch (Exception $exception) {
dd($exception->getMessage());
}
}
}

12. Add Routes for Laravel Facebook Login

For the controller functions, add the below routes in the web.php file:
Route::get('facebook', [SocialAuthController::class, 'facebookRedirect'])->name('auth/facebook');
Route::get('facebook/callback', [SocialAuthController::class, 'loginWithFacebook']);
After adding the routes, we will have to create a Facebook login button in the auth login page.

13. Create Facebook Login Button in Auth Login

The login.blade.php file has to look like this:

 

@extends('layouts.app')
@section('content')
{{ __('Login') }}
@csrf
{{ __('E-Mail Address') }}
@error('email')
{{ $message }}
@enderror
{{ __('Password') }}
@error('password')
{{ $message }}
@enderror
{{ __('Remember Me') }}
{{ __('Login') }}
{{ __('Login with Facebook') }}
@if (Route::has('password.request'))
{{ __('Forgot Your Password?') }}
@endif
@endsection


Next, We can check the result by running the application.

14. Check the Facebook Login feature in the Laravel application

Run the application and check the result. When you click on the Login option available by the Auth scaffolding, On the login page, you will see a button for Facebook login is available.
If working locally, you can test is via your web browser:
localhost:8000/login
When you will click on the Login with Facebook button, it will redirect you to the official login page with some parameters in the URL.



[Need assistance in fixing Laravel Application issues ? We can help you. ]


Conclusion

This article covers how to log in with a Facebook account in the Laravel 8 application using the Laravel Socialite composer package. In fact, Social login makes the authentication work facile by allowing site visitors to register and login on an application using their favorite social media accounts such as Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket.

Your Cart