Laravel 12 – How to Add Facebook Login Using Socialite and Livewire Auth.

Touseef Afridi
28 Nov 25

Laravel 12 – How to Add Facebook Login Using Socialite and Livewire Auth.

In this tutorial, we will learn how to implement Facebook login in Laravel 12 using Socialite and Livewire Auth, including OAuth setup, authentication flow, and secure user login integration.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through integrating Facebook login into a Laravel 12 application using Livewire authentication. It covers creating a fresh Laravel project, updating the users table and User model to store a facebook_id, and installing Laravel Socialite for Facebook OAuth support. You’ll configure a Facebook app in the Meta Developer Console, add the required credentials to your Laravel configuration, and create a controller to handle Facebook login and callback logic. Finally, you’ll define the necessary routes, add a Facebook login button to the registration view, and the integration is tested to ensure seamless authentication.

Step # 1 : Spin Up a New Laravel 12 Project with Livewire Authentication.

Start by creating a brand-new Laravel 12 application. If you already have the Laravel Installer available globally on your system, you can scaffold the project with the following command.
laravel new facebook
Alternatively, if the Installer is not set up, you can rely on Composer to create the project instead.
composer create-project laravel/laravel --prefer-dist facebook
Keep in mind that when you use Composer, the project is generated without any interactive prompts. This means you’ll need to manually configure authentication, testing tools, and frontend assets afterward. On the other hand, using the Laravel Installer walks you through a short setup wizard, which makes the initial configuration much easier. During the guided setup, choose these options.
  • Starter Kit: Select Livewire to enable Livewire powered authentication out of the box.
  • Authentication Provider: Use Laravel’s default authentication system for a straightforward setup.
  • Laravel Volt: Choose No, as Volt isn’t needed for this project.
  • Testing Framework: Pick Pest, a modern and expressive testing framework.
  • Frontend Dependencies: Select Yes so all necessary frontend packages are installed automatically.

After completing the setup, Laravel will generate a clean project with Livewire authentication ready to go, Pest configured for testing, SQLite set as the default database, and all standard migrations already in place.

Step # 2 : Move Into the Project Directory.

Open your terminal (Git Bash, Command Prompt, or PowerShell) and navigate to the root directory of your newly created Laravel application.
cd c:xampp/htdocs/facebook
This ensures that all upcoming Artisan and Composer commands are executed inside the correct project folder.

Step # 3 : Modify the Users Table and User Model.

To prepare your application for Facebook authentication, you first need to store each user’s Facebook identifier. Open the create_users_table migration file and add a new facebook_id column to the users table. This optional column will allow users to log in using Facebook even if they don’t set a traditional password.
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            //Add facebook id column.
            $table->string('facebook_id')->nullable();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
Next, update your User model (app/Models/User.php) by adding facebook_id to the $fillable array so it can be mass assigned.
protected $fillable = [
    'facebook_id',
    'name',
    'email',
    'password',
];
Since the project uses SQLite by default, you can reset and rebuild the database to apply the new schema.
php artisan migrate:fresh
This command drops all existing tables and recreates them, including the updated users table with the facebook_id column.

Step # 4 : Install Laravel Socialite.

To handle social authentication providers such as Facebook, We will use the Socialite package. Install it by running the following command from the project root.
composer require laravel/socialite
Composer will fetch Socialite and its dependencies, then automatically update your composer.json file. Once installed, your application is ready to be configured for Facebook login.

Step # 5 : Get Your Facebook App ID and App Secret.

To enable Facebook login, you first need to create a Facebook application and obtain your APP_ID and APP_SECRET. Follow these steps.
  1. Start by logging in to Meta for Developers at: https://developers.facebook.com/.
  2. Click Create App to begin setting up a new application.



  3. Enter a Name for your app (this is what users may see during login).



  4. Choose Authenticate and request data from users with Facebook Login, then continue.



  5. For this demo project, select I don’t want to connect a business portfolio yet.



  6. On the Publishing Requirements screen, simply click Next.



  7. Review the app details on the Overview page, then click Go to dashboard.



  8. From the left sidebar, open Use Cases.



  9. On the Use Cases Page click on Customize.



  10. Add the email permission by clicking Add (it’s not enabled by default).



  11. Make sure the email permission status shows Ready for Testing.



  12. To get your APP_ID and APP_SECRET, go to the left menu, select App Settings, then click on Basic. On this page, you’ll find both your APP_ID and APP_Secret. For local testing, you can ignore optional fields such as app domain, privacy policy URL, or app icon.



Next, open your Laravel project and update the config/services.php file by adding the Facebook configuration.
    //Facebook Login
    'facebook' => [
        'client_id' => env('FACEBOOK_APP_ID'),
        'client_secret' => env('FACEBOOK_APP_SECRET'),
        'redirect' => env('FACEBOOK_REDIRECT_URI'),
    ],
Then, open your .env file and define the required environment variables.
FACEBOOK_APP_ID="Define your app id here"
FACEBOOK_APP_SECRET="Define your app secret here"
FACEBOOK_REDIRECT_URI="http://localhost:8000/auth/facebook/callback"
At this point, your Laravel application is fully prepared to communicate with Facebook for authentication.

Step # 6 : Create the SocialController.

To manage the Facebook login flow, you’ll need a dedicated controller. Start by generating it with Artisan.
php artisan make:controller SocialController
Once the controller is created, open app/Http/Controllers/SocialController.php and update it as follows.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Exception;
class SocialController extends Controller
{
    public function facebookRedirect()
    {
        // Send the user to Facebook’s authentication page
        return Socialite::driver('facebook')->redirect();
    }
    public function loginWithFacebook()
    {
        try {
            // Fetch the authenticated user details from Facebook
            $facebookUser = Socialite::driver('facebook')
                ->stateless()
                ->user();
            // Look for an existing user using Facebook ID or email
            $user = User::where('facebook_id', $facebookUser->id)
                ->orWhere('email', $facebookUser->email)
                ->first();
            if ($user) {
                // If the user exists but Facebook ID is missing, update it
                if ($user->facebook_id !== $facebookUser->id) {
                    $user->update([
                        'facebook_id' => $facebookUser->id,
                    ]);
                }
                Auth::login($user);
            } else {
                // Create a new user if none exists
                $user = User::create([
                    'name' => $facebookUser->name,
                    'email' => $facebookUser->email,
                    'facebook_id' => $facebookUser->id,
                    'password' => bcrypt('password'),
                ]);
                Auth::login($user);
            }
            // Send the user to the dashboard after successful login
            return redirect('/dashboard');
        } catch (\Throwable $th) {
            // You may log this exception for easier debugging
            throw $th;
        }
    }
}
This controller contains two core methods. The facebookRedirect() method sends the user to Facebook’s login page & loginWithFacebook() method handles the callback, retrieves user data, checks for an existing account, and logs the user in or creates a new record if needed.

Step # 7 : Define the Facebook Authentication Routes.

Next, you need to register routes that connect Facebook login to your controller. Open your routes file routes/web.php, import the SocialController and add the following routes.
use App\Http\Controllers\SocialController;
// Route to redirect to Facebook for authentication
Route::get('auth/facebook', 'App\Http\Controllers\SocialController@facebookRedirect');
// Route to handle the callback from Facebook after authentication
Route::get('auth/facebook/callback', 'App\Http\Controllers\SocialController@loginWithFacebook');
With these routes in place, users can be redirected to Facebook for authentication and properly returned to your application once the login process is complete.

Step # 8 : Add the Facebook Login Link to the Register / Login View.

The final UI step is to expose Facebook login to users. Open your register Blade view and place the Facebook login button just below the default “Create Account” button.
<!-- OR separator -->
<div class="text-center">
    <span class="text-sm text-gray-600">OR</span>
</div>
<!-- Facebook login button -->
<div class="flex items-center justify-center">
    <a href="{{ url('auth/facebook') }}"
       class="inline-block w-full text-center px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-lg text-gray-800 font-semibold">
        Login with Facebook
    </a>
</div>
This adds a clear visual separator and a Login with Facebook button directly beneath the default authentication form. When clicked, users are redirected to Facebook to complete the login process.

Step # 9 : Test the Facebook Login Integration.

Now it’s time to verify everything works as expected. Start the Laravel development server by running.
php artisan serve
Once the server is running, visit your Register page in the browser. You should see the new Login with Facebook button. Clicking the button will redirect you to Facebook for authentication. After approving the permissions, you’ll be redirected back to your application and logged in automatically.



Conclusion

By following this guide, you've successfully integrated Facebook login into your Laravel 12 application using Livewire authentication, allowing users to register and sign in effortlessly with their Facebook accounts. With Laravel Socialite handling the OAuth flow, your application now provides a smooth and reliable social login experience alongside the default authentication system. You can further extend or customize this setup based on your project needs, such as adding more providers or refining user data handling.
For additional options and advanced configurations, refer to the Laravel Socialite documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
1

0 Comments

To engage in commentary, kindly proceed by logging in or registering