Login with Facebook in Laravel 9 with Socialite and Jetstream

In this tutorial, you will find out how to log in with Facebook in Laravel with the help of laravel socialite and jetstream packages.

Laravel offers an exorbitantly easy and simple way to authenticate with OAuth providers using Laravel Socialite.

Social authentication is one of the easiest mechanism to log in to web application, and you can log in to Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket with laravel socialite package.

However, this tutorial explains you specifically login with Facebook using your Facebook account in laravel app with Jetstream.

Jetstream is an authentication scaffolding specially built with Tailwind CSS.

It gives you pre-built auth templates on top of Livewire and Inertia scaffolding. In general, when you install and configure Jetstream in laravel, you get the following components:

  • Login
  • Registration
  • Email verification
  • Forgot password
  • Two-factor authentication

The laravel login with Facebook example makes the auth process facile, through this process you don’t have to fill the long-form to sign in, over and above that you don’t have to remember your login credentials.

Just one click on the large blue button and you are into the application.

Let’s create laravel login with Facebook feature.

Build Laravel Project

I assume you have already created the laravel project, if not then follow the given below command to install new laravel application:

composer create-project laravel/laravel --prefer-dist laravel-login-facebook

Make Database Connection

In this step you have to make the database connection in laravel, so open .env file further add your database details:

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

Install Jetstream Package

This step brings us to install Laravel Jetstream, and it will generate necessary application scaffolding.

So hit the following command to commence the installation:

composer require laravel/jetstream

Next, you have to install livewire with jetstream:

php artisan jetstream:install livewire

Install necessary NPM dependency:

npm install

Start node development server:

npm run dev

Migrate table into the database:

php artisan migrate

Install Laravel Socialite

Next, you have to install laravel socialite library, it will help to create login with facebook functionality.

composer require laravel/socialite

Then, head over to config/app.php app configuration file, moreover inject socialite class in providers, by the same token in aliases array:

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

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

Create Facebook Column in Users Table

Run the given below code to create a new Facebook column within the users’ table.

php artisan make:migration add_fb_id_column_in_users_table --table=users

Next, update the below code in migrations/add_fb_id_column_in_users_table.php:

<?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('id_fb')->nullable();
        });
    }

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

Next, define the new column in 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 Laravel\Fortify\TwoFactorAuthenticatable;
use Illuminate\Notifications\Notifiable;
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',
        'id_fb',
    ];

    /**
     * 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',
    ];
}

Define Client Id and App Id

First, you need a Facebook developer account to create Facebook Key and Secret, further conjugate the code in config/services file:

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

Setting Up Controller

Use below command to create a login controller:

php artisan make:controller LoginController

Open and add code in app/Http/Controllers/LoginController.php:

<?php

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

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

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

Create Route

Open and define below code to create routes in routes/web.php:

<?php

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

/*
|--------------------------------------------------------------------------
| 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('auth/facebook', [LoginController::class, 'redirect']);

Route::get('auth/facebook/callback', [LoginController::class, 'signinFacebook']);

Build Blade View

Ultimately, you have to create a blade view to display the login page. So, open and add below code in 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">
                    <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 --}}
            <div class="flex items-center justify-end mt-4">
                <a class="btn" href="{{ url('auth/facebook') }}"
                    style="background: #3B5499; color: WHITE; padding: 12px; width: 100%; text-align: center; border-radius:4px;  display: block;">
                    Login with Facebook
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

To test login with facebook, you need to run the development server:

php artisan serve

Open the app woth below URL:

http://127.0.0.1:8000/login

Conclusion

The Laravel Login with the Facebook example tutorial is over. Throughout, this tutorial we learned, how to easily signin with Facebook in laravel app using socialite plugin.

With the same laravel socialite package, you can also log in with other social media platforms such as Twitter, Google, LinkedIn, GitHub, GitLab, and Bitbucket.

Moreover, we also saw how to integrate Laravel Jetstream to set up laravel auth UI within a couple of minutes.

I hope you liked this tutorial. Kindly share it with others.