Get in touch: support@brackets-hub.com



How to Add Facebook Login using Socialite in Laravel

Create Facebook App:

Go to the Facebook Developers website and create a new app.
Note down the App ID and App Secret.

Install Socialite Package: Run the following composer command to install Socialite package:

composer require laravel/socialite

Configure Socialite:

Add your Facebook App ID and App Secret to your .env file:

FACEBOOK_CLIENT_ID=your-facebook-app-id
FACEBOOK_CLIENT_SECRET=your-facebook-app-secret
FACEBOOK_REDIRECT_URI=http://your-domain.com/auth/facebook/callback

Create Routes: Add the following routes to your routes/web.php file:

Route::get('/auth/facebook', 'Auth\LoginController@redirectToFacebook');
Route::get('/auth/facebook/callback', 'Auth\LoginController@handleFacebookCallback');

Create Controller Methods: Create methods in your Auth\LoginController to handle Facebook login:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Socialite;

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

    public function handleFacebookCallback()
    {
        $user = Socialite::driver('facebook')->user();

        // Your logic to handle the user after authentication
    }
}

Use Facebook Driver: Use the facebook driver in your config/services.php file:

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

That’s it! You have now added Facebook login using Socialite in your Laravel application. Make sure to handle the user data returned by Facebook according to your application’s requirements.

Test: Visit /auth/facebook in your browser, and you should be redirected to Facebook’s login page. After successful authentication, you’ll be redirected back to your application.

Leave a Reply

Your email address will not be published. Required fields are marked *