Laravel Socialite Facebook Login

 

To implement Facebook login using Laravel Socialite, follow these steps:


Step 1: Install Laravel Socialite

In your terminal, run the following command to install the Socialite package:


composer require laravel/socialite


Step 2: Configure Facebook OAuth Credentials

Visit the Facebook Developer Console (https://developers.facebook.com/), create a new app, and set up Facebook Login. Note down the App ID and App Secret.


Step 3: Configure Services in Laravel

Open `config/services.php` and add the Facebook OAuth credentials:


'facebook' => [

    'client_id' => env('FACEBOOK_APP_ID'),

    'client_secret' => env('FACEBOOK_APP_SECRET'),

    'redirect' => env('FACEBOOK_REDIRECT_URI'),

],


Step 4: Create Routes

In your `routes/web.php`, create routes for social login:


Route::get('auth/facebook', 'Auth\SocialController@redirectToFacebook');

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


Step 5: Create Controller

Generate a controller using the following command:


php artisan make:controller Auth/SocialController


In `Auth/SocialController.php`, implement the following methods:


use Laravel\Socialite\Facades\Socialite;


public function redirectToFacebook()

{

    return Socialite::driver('facebook')->redirect();

}


public function handleFacebookCallback()

{

    $user = Socialite::driver('facebook')->user();


    // $user contains user details received from Facebook


    // You can now authenticate the user or perform other actions


    return redirect()->route('home'); // Redirect after successful login

}


Step 6: Update .env File

Add your Facebook OAuth credentials to your `.env` file:


FACEBOOK_APP_ID=your_facebook_app_id

FACEBOOK_APP_SECRET=your_facebook_app_secret

FACEBOOK_REDIRECT_URI=http://your-app-url/auth/facebook/callback


Replace `your_facebook_app_id` and `your_facebook_app_secret` with your actual credentials.


Step 7: Implement Login Button

In your view, create a link/button to initiate the Facebook login process:


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


That's it! Users can now click the "Login with Facebook" link/button, and they will be redirected to Facebook for authentication. Upon successful authentication, they will be redirected back to your application with user data.


Remember to handle user data appropriately, possibly by creating a new user or authenticating an existing user in your database. Also, customize the redirection and user management as per your application's requirements.