Laravel 13 - How to Integrate Facebook Login Using Socialite.
Laravel 13 - How to Integrate Facebook Login Using Socialite.
In this tutorial, we will learn how to add Facebook Login to Laravel 13 using Laravel Socialite and Livewire, configure Meta app credentials, implement Facebook authentication, and test the complete login integration step by step.
Quick Overview
This guide walks you through integrating Facebook login into a Laravel 13 application using Livewire authentication. It covers setting up a new Laravel project, updating the users table and User model to store the facebook_id, and installing Laravel Socialite for Facebook OAuth authentication. You’ll configure a Facebook app through Meta for Developers, add the required credentials to your Laravel configuration, and implement a controller to manage the Facebook authentication and callback process. Finally, you’ll define the necessary routes, add a Facebook login button to the Register / Login view, and test the integration to verify that users can authenticate successfully through Facebook.
Step # 1 : Initialize and Configure a Laravel 13 Project.
Start by creating a new Laravel 13 application named facebook using the Laravel Installer. Ensure Composer is installed before proceeding. If the Installer is not available on your system, install it globally with the following command.
composer global require laravel/installer
Once installed, generate the project by running.
laravel new facebook
During project initialization, Laravel will prompt you to configure several options. Choose the following settings to prepare the application for the Facebook login implementation.
- Starter Kit: Choose Yes to include a starter kit during the project setup.
- Authentication: Select Livewire to set up the authentication interface and supporting components.
- Authentication Provider: Use Laravel’s built-in authentication system to handle user authentication.
- Single-File Livewire Components: Choose Yes to organize each Livewire component’s logic and template within a single file.
- Teams Support: Select No, as team management is outside the scope of this project.
- Authentication Features: Select Registration to enable account creation for new users.
- Boost Features: Choose None by pressing Enter to skip optional Boost features.
- Third-Party AI Guidelines and Skills: Press Enter without selecting any options to skip these additions.
- Boost Integrations: Keep the default configuration and press Enter to proceed.
- AI Agent: Select Amp to configure the project for the Amp AI coding agent.
Once the setup process is complete, Laravel will generate the application named facebook using the selected Livewire starter kit and authentication options. The project will also include the Boost and AI-agent configuration selected during initialization.
Step # 2 : Navigate to the Laravel Project Directory.
After creating the application, open your preferred terminal and move into the newly generated facebook project directory. You can use PowerShell, Command Prompt, Git Bash, or the integrated terminal in Visual Studio Code. Execute the following command.
cd facebook
You can now run Laravel Artisan commands and manage the application from its root directory.
Step # 3 : Add Facebook Authentication Support to the User Model.
To support Facebook authentication, the application needs a field to store each user's Facebook account ID. Open the create_users_table migration file and add a nullable facebook_id column to the users table, as shown below.
Schema::create('users', function (Blueprint $table) {
$table->id();
$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();
});
The facebook_id column is nullable because users registering through other authentication methods may not have a Facebook ID associated with their account. Next, open app/Models/User.php and include facebook_id in the model's fillable attributes to allow mass assignment.
#[Fillable(['name', 'email', 'password', 'facebook_id'])]
Since this is a fresh project, you can apply the updated schema by running the following command.
php artisan migrate:fresh
This command removes existing tables and runs all migrations again, creating the database structure with the new facebook_id column.
Step # 4 : Install Laravel Socialite for Facebook Login.
Laravel Socialite simplifies OAuth authentication with supported providers, including Facebook. To add the package to your application, execute the following command from the project directory.
composer require laravel/socialite
Composer will download Socialite and its required dependencies, then register the package in your project's dependency configuration. Once installation is complete, you can proceed with configuring Facebook as an authentication provider.
Step # 5 : Configure Meta Developer Credentials for Facebook Authentication.
To integrate Facebook authentication into your Laravel 13 application, you first need to create an application on Meta for Developers and obtain its App ID and App Secret. These credentials allow Laravel Socialite to communicate with Facebook's authentication service. Start by visiting Meta for Developers at https://developers.facebook.com/ and signing in to your account. Once logged in, follow the steps below to create and configure your Facebook authentication.
- Click Create App to begin the application registration process.
- Provide a name for your application and proceed to the next step. This name will be displayed to users during the Facebook login process.
- Choose Authenticate and request data from users with Facebook Login as the use case, then continue.
- For this demonstration, select I don't want to connect a business portfolio yet to proceed without linking a business portfolio.
- On the Publishing Requirements screen, click Next to continue the setup.
- Review the information displayed on the Overview page, then click Create App to finalize the initial configuration.
- From the left-hand navigation menu, select Use Cases to access the available authentication options.
- Find the Facebook Login use case and click Customize to configure its settings.
- Locate the email permission and select Add to enable it, as this permission may not be included by default.
- Check that the email permission's status is displayed as Ready for Testing before moving forward.
- To retrieve your App ID and App Secret, navigate to App Settings → Basic using the sidebar. Both credentials are available on this page. For local development, optional details such as the app domain, privacy policy URL, and app icon can generally be left unconfigured unless Meta requires them for your setup.
Once you have obtained your Facebook credentials, open config/services.php in your Laravel project and register the Facebook service configuration within the existing array.
// Facebook Authentication
'facebook' => [
'client_id' => env('FACEBOOK_APP_ID'),
'client_secret' => env('FACEBOOK_APP_SECRET'),
'redirect' => env('FACEBOOK_REDIRECT_URI'),
],
Next, update your .env file with the following environment variables. Replace the placeholder values with your actual App ID and App Secret, and make sure the redirect URI matches the callback route configured in your application.
FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret
FACEBOOK_REDIRECT_URI=http://localhost:8000/auth/facebook/callback
With the Facebook credentials and service configuration in place, your Laravel application is ready for the next stage of the integration, where you will implement the routes and authentication logic required to handle Facebook login.
Step # 6 : Implement Facebook Authentication in the SocialController.
To handle Facebook authentication in a structured way, create a dedicated controller that manages the redirect to Facebook and processes the authentication callback. Generate the controller using Laravel Artisan command.
php artisan make:controller SocialController
After generating the controller, open app/Http/Controllers/SocialController.php and replace its contents with the following code.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
class SocialController extends Controller
{
public function facebookRedirect()
{
// Redirect the user to Facebook for authentication
return Socialite::driver('facebook')->redirect();
}
public function loginWithFacebook()
{
// Retrieve the user's Facebook profile information
$facebookUser = Socialite::driver('facebook')
->stateless()
->user();
// Find an account using the Facebook ID or email address
$user = User::where('facebook_id', $facebookUser->id)
->orWhere('email', $facebookUser->email)
->first();
if ($user) {
// Link the Facebook ID if it is not already associated
if ($user->facebook_id !== $facebookUser->id) {
$user->update([
'facebook_id' => $facebookUser->id,
]);
}
} else {
// Create a new account using the Facebook profile details
$user = User::create([
'name' => $facebookUser->name,
'email' => $facebookUser->email,
'facebook_id' => $facebookUser->id,
'password' => Hash::make(Str::random(32)),
]);
}
// Sign in the user and redirect to the dashboard
Auth::login($user);
return redirect('/dashboard');
}
}
The facebookRedirect() method initiates the login process by sending the user to Facebook. Once Facebook redirects the user back to the application, loginWithFacebook() retrieves the profile details and checks whether an account already exists using the Facebook ID or email address. If a matching account is found, its Facebook ID is linked when necessary; otherwise, a new account is created with a randomly generated password hash. Finally, Laravel authenticates the user and redirects them to the dashboard.
Step # 7 : Configure the Routes for Facebook Login.
To connect Facebook authentication with your controller, you need to define the appropriate routes in your Laravel application. Open routes/web.php, import the SocialController, and register the following routes.
use App\Http\Controllers\SocialController;
// Redirect users to Facebook for authentication
Route::get('/auth/facebook', [SocialController::class, 'facebookRedirect']);
// Handle the callback after Facebook authentication
Route::get('/auth/facebook/callback', [SocialController::class, 'loginWithFacebook']);
The first route redirects users to Facebook to authenticate their accounts, while the callback route processes the response and completes the login flow in your application. Make sure the callback URL matches the redirect URI configured in your Facebook app settings and your .env file.
Step # 8 : Add the Facebook Login Button to the Register / Login View.
To give users an alternative way to authenticate, add a Login with Facebook button to your registration page. Open your registration Blade view and place the following code immediately after the closing </form> tag, beneath the Create account button.
<!-- OR separator -->
<div class="flex items-center justify-center">
<span class="px-3 text-sm text-gray-500 dark:text-gray-400">
OR
</span>
</div>
<!-- Facebook login button -->
<div class="flex items-center justify-center">
<a
href="{{ url('/auth/facebook') }}"
class="flex w-full items-center justify-center rounded-lg bg-gray-200 px-4 py-2 font-semibold text-gray-800 hover:bg-gray-300 dark:bg-zinc-800 dark:text-white dark:hover:bg-zinc-700"
>
Login with Facebook
</a>
</div>
This adds a visual separator and a Facebook login button below the registration form. When clicked, users are redirected to Facebook to authenticate and then returned to your application through the configured callback route. You can also add the same button to your login page if you want to offer Facebook authentication there as well.
Step # 9 : Verify Facebook Authentication in Your Laravel 13 Application.
With the configuration and implementation complete, it's time to test Facebook authentication in your Laravel 13 application. Start the Laravel development server by running the following command in your terminal.
php artisan serve
Once the server is running, open your application's registration page in your browser. You should see the Login with Facebook button below the registration form. Click the button to begin the Facebook authentication process. You will be redirected to Facebook, where you can authorize the requested permissions. After successful authentication, Facebook will redirect you back to your application, where you should be logged in and redirected to the dashboard.
If the authentication flow completes successfully, your Facebook login integration is working as expected.
Conclusion
By following this guide, you've successfully integrated Facebook login into your Laravel 13 application using Livewire authentication, allowing users to authenticate with their Facebook accounts alongside the default authentication system. With Laravel Socialite managing the OAuth process, your application can redirect users to Facebook, retrieve their profile information, and log them in after successful authentication. You can further enhance this implementation by improving account linking, handling missing user information, and adding support for other social login providers as your project evolves.
For more details and advanced configuration options, refer to the official Laravel Socialite documentation: https://laravel.com/docs/13.x/socialite.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments