How to implement Facebook Login in Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

In this tutorial, we will learn how to integrate Facebook Login into a Laravel application. Authenticating users with their Facebook accounts can improve the user experience by enabling quick sign-ups and logins without requiring them to remember another set of credentials. We’ll be using Laravel Socialite, an official Laravel package that simplifies social authentication.

Before starting, ensure that you have Laravel installed on your system, as well as Composer to manage the dependencies. Also, you will need a Facebook Developer account to create a new Facebook application.

Set Up a New Facebook App

First things first, log in to the Facebook Developer Console. Create a new app and specify the display name and contact email. Go to the app’s settings and find the ‘Facebook Login’ section. Add your website’s URL to the Valid OAuth Redirect URIs.

Take note of the App ID and App Secret provided by Facebook. These will be used to configure your Laravel application.

Installing Laravel Socialite

To get started with Socialite, install it using Composer with the following command:

composer require laravel/socialite

This will download and install Socialite and its dependencies. After installation, you must register the Socialite service provider in your config/app.php file:

'providers' => [
    // Other service providers...

    Laravel\Socialite\SocialiteServiceProvider::class,
],

Configuring Socialite

Add the Facebook driver information to the config/services.php:

'facebook' => [
    'client_id' => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect' => env('FACEBOOK_REDIRECT'),
],

Update your .env file with the Facebook App details:

FACEBOOK_CLIENT_ID=your-app-id
FACEBOOK_CLIENT_SECRET=your-app-secret
FACEBOOK_REDIRECT=http://your-callback-url

Authenticating Users with Facebook

Create authentication scaffold in your Laravel project with this Artisan command:

php artisan make:auth

Edit the auto-generated App\Http\Controllers\Auth\LoginController.php and include the Socialite namespace:

use Socialite;

Add methods to handle the OAuth flow:

public function redirectToProvider($provider)
{
    return Socialite::driver($provider)->redirect();
}

public function handleProviderCallback($provider)
{
    $user = Socialite::driver($provider)->user();

    // Add user to the database or log them in

    return redirect()->to('/home');
}

In the routes/web.php, add routes to handle the Facebook OAuth redirects:

Route::get('login/{provider}', 'Auth\LoginController@redirectToProvider');
Route::get('login/{provider}/callback', 'Auth\LoginController@handleProviderCallback');

Creating The Frontend

Update your views to include a ‘Login with Facebook’ button. In resources/views/auth/login.blade.php, add:

<a href="{{ url('/login/facebook') }}">Login with Facebook</a>

Migrating and Setting Up the Users Table

Run the migrations to set up the users table:

php artisan migrate

In app/User.php, ensure that your user model can store the necessary Facebook data. You might need to add fields such as facebook_id.

Storing User Data

In the LoginController, update the handleProviderCallback method to store or update the user in your database, then log them in:

public function handleProviderCallback($provider)
{
    $socialUser = Socialite::driver($provider)->user();
    $user = User::where('facebook_id', $socialUser->getId())->first();

    if ($user) {
        Auth::login($user);
    } else {
        $user = User::create([
            'name' => $socialUser->getName(),
            'email' => $socialUser->getEmail(),
            'facebook_id' => $socialUser->getId(),
            // Set other fields as needed.
        ]);
        Auth::login($user);
    }

    return redirect()->to('/home');
}

Now, when a user clicks ‘Login with Facebook’, they will be redirected to the Facebook authentication page, and after allowing permissions, redirected back to your Laravel app where their user information will be handled according to the code below.

What’s Next?

After getting the basics working, you might want to handle cases where a user’s email is not returned by Facebook or develop a linking strategy for users signed up with the same email. By updating your login and registration logic, you can create seamless transitions between OAuth and traditional authentication.

Conclusion

Integrating Facebook Login into your Laravel application provides a convenient authentication mechanism for your users. With Laravel Socialite, the process is streamlined and can be customized to fit your project’s needs. Remember to handle user data respectfully and in accordance with privacy laws.