Laravel 11 - How to integrate Facebook Login
Laravel 11 - How to integrate Facebook Login
In this tutorial, we will discuss how to integrate Facebook login in Laravel 11, making authentication easier and enhancing user experience with social login.
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 project with Breeze. It starts with setting up a fresh Laravel project and modifying the users table to include a facebook_id field. You'll then install Laravel Socialite for OAuth authentication and configure Facebook credentials in your .env and services.php files. A SocialController is created to handle Facebook authentication, including user login or registration. Routes are set up for the Facebook login redirection and callback. Lastly, the Facebook login button is added to your Blade view, and the integration is tested to ensure seamless authentication.
Step # 1 : Create fresh Laravel project with Breeze Authentication.
If Laravel is installed globally, run the following command to create a new project.
laravel new facebook
Or
Alternatively, if Laravel is not installed globally, you can use Composer.
composer create-project laravel/laravel --prefer-dist facebook
After executing one of the above commands, you will be prompted.
- Would you like to install the starter kit? — Choose Breeze
- After selecting Breeze, you'll be asked to choose your stack. — Choose Blade
- After selecting Blade, you'll be asked for dark mode support. — Choose no
- After selecting No, you'll be asked about testing framework. — Choose Pest
- After selecting Pest, you'll be asked if you want to initialize git repo. — Choose no
- After selecting no, you'll be asked to select the database for your application. — Choose mysql
- After selecting MySql, you'll be asked if you want to run the default database migration. — Choose no
As we will be adding an additional field for facebook_id.
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to the root folder of your Laravel project.
cd c:xampp/htdocs/facebook
Step # 3 : Modify the Users Table & User Model.
Open the migration file create_users_table and add a new column facebook_id to the users table.
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();
});
Next, in the User model (app/Models/User.php), add facebook_id to the $fillable array to allow mass assignment.
protected $fillable = [
'facebook_id',
'name',
'email',
'password',
];
Finally, run the migration.
php artisan migrate
This will add the new facebook_id column to your users table, along with creating all necessary tables when the migration is executed.
Step # 4 : Install Socialite package.
To enable social authentication, install the Socialite package by running the following command.
composer require laravel/socialite
After running this command, Composer will download and install the Socialite package along with its dependencies. The composer.json file will be updated to include Socialite, making it ready for integration in your Laravel application.
Step # 5 : Obtain Your Facebook APP_ID and APP_SECRET.
To set up Facebook login, you'll need to create a Facebook app and obtain your APP_ID and APP_SECRET. Follow these steps.
Login to Meta for Developers (Link : https://developers.facebook.com/)
Click on Create App.
Select Authenticate and request data from users with Facebook Login.
Choose I don’t want to connect a business portfolio yet (optional for this example).
Enter a name for your App.
Click Go to Dashboard.

Navigate to Use Cases, and click Customize.
Navigate to Use Cases, and click Customize.
Assign the email permission (not enabled by default) by clicking Add.
Ensure the email permission shows as Ready for Testing.
To get your APP_ID and APP_SECRET, go to the left menu, select App Settings, then click on Basic. On the settings page, you'll find both APP_ID and APP_SECRET. For testing purposes, you can skip filling in optional details like domain, app icon, etc.
In your Laravel project, go to config/services.php and add the following Facebook authentication configuration.
//Facebook Login
'facebook' => [
'client_id' => env('FACEBOOK_APP_ID'),
'client_secret' => env('FACEBOOK_APP_SECRET'),
'redirect' => env('FACEBOOK_REDIRECT_URI'),
],
Next, open your .env file and define the keys and redirect URL.
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"
Make sure the redirect URL matches the one set in the Facebook Developer Console. Update the port if necessary (e.g., 8000 for Laravel’s built-in server) or remove it if using a different environment.
Step # 6 : Create SocialController.
To handle Facebook authentication, create a new controller by running the following command.
php artisan make:controller SocialController
Then, update the SocialController.php file to manage the Facebook authentication flow.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Socialite;
use Auth;
class SocialController extends Controller
{
public function facebookRedirect()
{
// Redirect to Facebook for authentication
return Socialite::driver('facebook')->redirect();
}
public function loginWithFacebook()
{
try {
// Retrieve user from Facebook
$facebookUser = Socialite::driver('facebook')->stateless()->user();
// Attempt to find an existing user by Facebook ID or email
$existingUser = User::where('facebook_id', $facebookUser->id)
->orWhere('email', $facebookUser->email)
->first();
if ($existingUser) {
// Update Facebook ID if the user was found by email
if ($existingUser->facebook_id !== $facebookUser->id) {
$existingUser->facebook_id = $facebookUser->id;
$existingUser->save();
}
Auth::login($existingUser);
} else {
// Create a new user
$createUser = User::create([
'name' => $facebookUser->name,
'email' => $facebookUser->email,
'facebook_id' => $facebookUser->id,
'password' => bcrypt('password'), // Hashing the password
]);
Auth::login($createUser);
}
// Redirect to the dashboard without the fragment
return redirect()->to('/dashboard'); // Ensure this is the direct path to your dashboard
} catch (\Throwable $th) {
// Handle the exception or log it
throw $th; // Consider logging the exception for debugging
}
}
}
This controller includes two main methods facebookRedirect(), which redirects the user to Facebook for authentication, and loginWithFacebook(), which handles the callback, retrieves user data from Facebook, checks for an existing user, and either logs them in or creates a new user if necessary.
Step # 7 : Set Up routes.
Import the SocialController class and define the routes for Facebook authentication.
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');
This ensures users can be redirected to Facebook for login and properly handle the callback once authenticated.
Step # 8 : Add Facebook login href to your Register/Login blade.
You can add the Facebook login button after the register button in your Blade view. Here’s an example.
<!-- Register button -->
<!-- Separator OR section -->
<div class="text-center mt-4">
<span class="text-sm text-gray-600">OR</span>
</div>
<!-- Login with Facebook button -->
<div class="flex items-center justify-center mt-4">
<x-secondary-button>
<a href="{{ url('auth/facebook') }}">
Login with Facebook
</a>
</x-secondary-button>
</div>
This integrates the Facebook login option into your registration/login page.
Step # 9 : It's time to test.
Run the project and access the Login/Register page to test the Facebook login integration.
php artisan serve
Once the server is running, you should be able to login and register using Facebook.
Conclusion
By following this guide, you've successfully integrated Facebook login into your Laravel project with Breeze authentication, enabling users to register and log in seamlessly using their Facebook accounts. With Socialite managing the authentication flow, your application now offers a convenient and secure login option. You can further customize the integration to meet your specific requirements.
For more details, check the Laravel Socialite documentation.
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