Laravel 8 Login with Facebook using Laravel Socialite

This Laravel 8 social login reference guide will talk about how to log in with a Facebook account in the Laravel 8 application using the Laravel Socialite composer package.

There are a couple of ways to authenticate in an application; nonetheless, OAuth is the user-friendly way of authenticating; in this tutorial, we will learn how to login with Facebook in the Laravel application using the Laravel Socialite.

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.

Laravel socialite makes developers’ life easy by giving them the freedom to authenticate users in-app. Social login lays an extra layer of verification and makes sure the user is a real person. Consequently, it enhances the user experience and allows users to provide their information without extra effort.

How to login with Facebook in Laravel 8 application. If you have the same question, then get along; throughout this tutorial, we will learn how to login using Facebook social media account in Laravel using the Socialite package.

Login with a social account is not that easy; nonetheless, socialite makes the authentication process less complicated through its robust coding boilerplate. An authentication process is incomplete without the authentication user interface; however, creating UI is a time-consuming process. Fret not, and we will use Laravel Jetstream to build fast and responsive authentication UI in the Laravel application.

So, without wasting much time, Let’s start creating Laravel 8 Login with Facebook using Laravel Socialite.

Create Laravel App

Move to console, run command to create a new Laravel project:

composer create-project laravel/laravel --prefer-dist laravel-socialite-tutorial

Connect to Database

Add the database name, user name, password in .env file to establish the consensus.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database
DB_USERNAME=root
DB_PASSWORD=

Add Jetstream

Laravel Jetstream is a beautifully crafted application scaffolding for Laravel. Jetstream offers login, registration, email verification, two-factor authentication, and session management.

Run command to install Laravel jetstream:

composer require laravel/jetstream

Create login, register and email verification pages.

php artisan jetstream:install livewire

Now, run command to build assets.

npm install && npm run dev

Run migration command.

php artisan migrate

Install Laravel Socialite

Run composer command to install the Laravel socialite package.

composer require laravel/socialite

Inject socialite class in providers, and aliases array in config/app.php file.

....
....
'providers' => [
    ....
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
],

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

Migrate Facebook ID in Users Auth Table

To login with Facebook in Laravel application, your Users table must have a facebook_id, so add it by running the below command.

php artisan make:migration add_facebook_id_column_in_users_table --table=users

Open timestamp_add_facebook_id_column_in_users_table.php and place the below code inside.

<?php

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

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

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

Open app/Models/User.php, and include the Facebook ID property.

<?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;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

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

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

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

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}

Register Facebook App ID and Secret

Next, visit developers.facebook.com/apps tool, create Facebook app id and secret, then register both id and secret in config/services file.

return [
    ....
    'facebook' => [
        'client_id' => 'App id goes here',
        'client_secret' => 'Secret goes herre',
        'redirect' => 'http://localhost:8000/auth/facebook/callback',
    ],
]

Create Route

Now register the routes for login with facebook in routes/web.php.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FbController;


Route::get('auth/facebook', [FbController::class, 'redirectToFacebook']);

Route::get('auth/facebook/callback', [FbController::class, 'facebookSignin']);

Create Controller

Run command to create a new controller.

php artisan make:controller FbController

Add below code in app/Http/Controllers/FbController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Models\User;
use Validator;
use Socialite;
use Exception;
use Auth;

class FbController extends Controller
{
    public function redirectToFacebook()
    {
        return Socialite::driver('facebook')->redirect();
    }

    public function facebookSignin()
    {
        try {
    
            $user = Socialite::driver('facebook')->user();
            $facebookId = User::where('facebook_id', $user->id)->first();
     
            if($facebookId){
                Auth::login($facebookId);
                return redirect('/dashboard');
            }else{
                $createUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'facebook_id' => $user->id,
                    'password' => encrypt('john123')
                ]);
    
                Auth::login($createUser);
                return redirect('/dashboard');
            }
    
        } catch (Exception $exception) {
            dd($exception->getMessage());
        }
    }
}

Update Login View

Finally, you need to place the Login with Facebook button view template, open views/auth/login.blade.php and place the below code.

<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label for="email" value="{{ __('Email') }}" />
                <x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label for="password" value="{{ __('Password') }}" />
                <x-jet-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label for="remember_me" class="flex items-center">
                    <input id="remember_me" type="checkbox" class="form-checkbox" name="remember">
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Login') }}
                </x-jet-button>
            </div>

            {{-- Login with Facebook Component --}}
            <div class="flex items-center justify-end mt-4">
                <a class="btn" href="{{ url('auth/facebook') }}"
                    style="background-color: #3B5499; color: #ffffff; padding: 8px; width: 100%; text-align: center; display: block; border-radius:4px;">
                    Login with Facebook
                </a>
            </div>            
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Run the command to open the authentication app.

php artisan serve

Open the below URL:

http://127.0.0.1:8000/login

Laravel 8 Login with Facebook using Laravel Socialite

Finally, Laravel 8|7 Login with Facebook tutorial is over, i hope you liked this example.

Download complete code: https://github.com/remotestack377/LaravelSocialiteTutorial