Laravel 10 Login with Facebook Account

In Laravel, the "Login with Facebook" feature is implemented to allow users to authenticate and log into a website or application using their Facebook credentials. 

Step 1: Install Laravel 10

composer create-project laravel/laravel example-app

  Step 2: Install JetStream

let's run bellow command and install bellow library. 

composer require laravel/jetstream

now, we need to create authentication using bellow command. you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. you can see bellow commands:

php artisan jetstream:install livewire

we need to run migration command to create database table:

php artisan migrate

Step 3: Install Socialite

In below step we will install Socialite Package that provide api to connect with facebook account. So, run bellow command: 

composer require laravel/socialite

Step 4: Create Facebook App

First we need to create Facebook App and get ID and Secret. So, let's follow bellow steps: 

Step 1: Go to Facebook Developer App to click here: https://developers.facebook.com

Step 2: Then click to "Create App" button 

Step 3: Then Choose Select Type as consumer 

Step 4: Then Add App name , then after click to create app button

Step 5: Now, you will get app id and secret, Then you need to add this details to .env file

Step 6: If you want to upload on production then you need to  add domain into share Redirect Domain Allow List . But, you are checking with local then you don't need to add this URLs:

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.php

return [
    ....
    'facebook' => [
        'client_id' => env('FACEBOOK_CLIENT_ID'),
        'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
        'redirect' => env('FACEBOOK_CALLBACK_URL'),
    ],
]

.env

FACEBOOK_CLIENT_ID=xyz
    FACEBOOK_CLIENT_SECRET=123
    FACEBOOK_CALLBACK_URL=http://localhost:8000/auth/facebook/callback

Step 5: Add Database Column

In this step first we have to create migration for add facebook_id in your user table. So let's run bellow command: 

php artisan make:migration add_facebook_id_column

Migration

<?php
  
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
      
    return new class extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up(): void
        {
            Schema::table('users', function ($table) {
                $table->string('facebook_id')->nullable();
            });
        }
      
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down(): void
        {
              
        }
    };

Update mode like this way:

app/Models/User.php

<?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 string[]
         */
        protected $fillable = [
            'name',
            'email',
            'password',
            'facebook_id'
        ]; 
     
        /**
         * The attributes that should be hidden for serialization.
         *
         * @var array
         */
        protected $hidden = [
            'password',
            'remember_token',
            'two_factor_recovery_codes',
            'two_factor_secret',
        ];
      
        /**
         * The attributes that should be cast.
         *
         * @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',
        ];
    }

Step 6: Create Routes

routes/web.php 

<?php
  
    use Illuminate\Support\Facades\Route;
      
    use App\Http\Controllers\GoogleController;
      
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
      
    Route::get('/', function () {
        return view('welcome');
    });
      
    Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
        return view('dashboard');
    })->name('dashboard');
      
    Route::controller(FacebookController::class)->group(function(){
        Route::get('auth/facebook', 'redirectToFacebook')->name('auth.facebook');
        Route::get('auth/facebook/callback', 'handleFacebookCallback');
    });

Step 7: Create Controller

app/Http/Controllers/FacebookController.php

<?php
  
    namespace App\Http\Controllers;
      
    use Illuminate\Http\Request;
    use Laravel\Socialite\Facades\Socialite;
    use Exception;
    use App\Models\User;
    use Illuminate\Support\Facades\Auth;
      
    class FacebookController extends Controller
    {
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function redirectToFacebook()
        {
            return Socialite::driver('facebook')->redirect();
        }
               
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function handleFacebookCallback()
        {
            try {
            
                $user = Socialite::driver('facebook')->user();
             
                $finduser = User::where('facebook_id', $user->id)->first();
             
                if($finduser){
             
                    Auth::login($finduser);
           
                    return redirect()->intended('dashboard');
             
                }else{
                    $newUser = User::updateOrCreate(['email' => $user->email],[
                            'name' => $user->name,
                            'facebook_id'=> $user->id,
                            'password' => encrypt('123456dummy')
                        ]);
            
                    Auth::login($newUser);
            
                    return redirect()->intended('dashboard');
                }
           
            } catch (Exception $e) {
                dd($e->getMessage());
            }
        }
    }

Step 8: Update Blade File

resources/views/auth/login.blade.php 

<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">
                    <x-jet-checkbox id="remember_me" 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">
                    {{ __('Log in') }}
                </x-jet-button>
            </div>
            <div class="flex items-center justify-end mt-4">
                <a class="ml-1 btn btn-primary" href="{{ url('auth/facebook') }}" style="margin-top: 0px !important;background: blue;color: #ffffff;padding: 5px;border-radius:7px;" id="btn-fblogin">
                    <i class="fa fa-facebook-square" aria-hidden="true"></i> Login with Facebook
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Run Laravel App:

php artisan serve

Now, Go to your browser, type the given URL and view the output:

http://localhost:8000/login