Laravel Socialite Facebook Login
Tags: laravel, php, programming, tutorial
Published: 2021-08-08 16:49:31

In this post i am going to explain about Laravel Socialite Authentication using Facebook.

To Start with follow the below steps.

### STEP 1
Install Laravel Socialite Package using composer.

```php
composer require laravel/socialite
```
NOTE: If Using Laravel lower than version 8 Include Package in Providers.
In `config/app.php` file add the below provider

```php
Laravel\Socialite\SocialiteServiceProvider::class,
```

Scroll Down to aliases section and add below code

```php
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
```

### Step 2
Include Facebook Service in `config/services.php` file.
```php
'facebook' => [
        'client_id' => '', //USE FROM FACEBOOK DEVELOPER ACCOUNT
        'client_secret' => '', //USE FROM FACEBOOK DEVELOPER ACCOUNT
        'redirect' => 'https://examplelaravel8.test/facebook/callback/'
    ],
```

### STEP 3
Here, you have to create Facebook app so that you can get a `client_id` and `client_secret` from Facebook.

You can do this by going to Facebook’s [developers URL]( https://developers.facebook.com/)
 
and log in with your Facebook account.

Go to `My Apps`, proceed to `Add New App`

### STEP 4
Create a new controller to handle socialite action. Run below command to generate a new controller

```php
php artisan make:controller FaceBookController
```

Update FacebookController With Code Below Which have 2 Function To Redirect and To handle Callback.

```php
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Facades\Socialite;

class FaceBookController extends Controller
{
/**
 * Login Using Facebook
 */
 public function loginUsingFacebook()
 {
    return Socialite::driver('facebook')->redirect();
 }

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

       $saveUser = User::updateOrCreate([
           'facebook_id' => $user->getId(),
       ],[
           'name' => $user->getName(),
           'email' => $user->getEmail(),
           'password' => Hash::make($user->getName().'@'.$user->getId())
            ]);

       Auth::loginUsingId($saveUser->id);
            
       return redirect()->route('home');
       } catch (\Throwable $th) {
          throw $th;
       }
   }
}
```

### STEP 5
Add Facebook authentication routes

```php
// Facebook Login URL
Route::prefix('facebook')->name('facebook.')->group( function(){
    Route::get('auth', [FaceBookController::class, 'loginUsingFacebook'])->name('login');
    Route::get('callback', [FaceBookController::class, 'callbackFromFacebook'])->name('callback');
});
```

### STEP 6
ADD Facebook Button on Login Page `resources/views/auth/login.blade.php`

```php
 <a href="{{ route('facebook.login') }}" class="btn btn-facebook btn-user btn-block">
   <i class="fab fa-facebook-f fa-fw"></i>
   Login with Facebook
</a>
```

### STEP 7
Add `facebook_id` Column in Users table, create a migration be command below
```php
php artisan make:migration add_facebook_id_in_users_table
```

Add Below Code in Migration file
```php
 /**
 * Run the migrations.
 *
 * @return void
 */
 public function up()
 {
    Schema::table('users', function (Blueprint $table) {
        $table->string('facebook_id')->nullable();
    });
 }

 /**
 * Reverse the migrations.
 *
 * @return void
 */
 public function down()
 {
   Schema::table('users', function (Blueprint $table) {
       $table->dropColumn('facebook_id');
   });
 }
```

and run migration

```php
php artisan migrate
```

###STEP 8

Update The User Model Fillable Property in `Models/User.php`

```php
protected $fillable = [
        'name',
        'email',
        'password',
        'status',
        'facebook_id'
];
```

Finally Go To Login Page And Try Accessing Login With Facebook Button.

![Facebook Login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/88s8nvvv196r12000wq5.png)

If you get any issue while integrating it, do comment your problems. 

Get Code on [Techtool Github](https://github.com/TechTool-India/ExampleProject/tree/social-login)

You can watch this video I have explained this.

{% youtube 753IURNzPvU %}


Thank You for Reading

Reach Out To me.
[Twitter](https://twitter.com/techtoolindia)
[Instagram](https://www.instagram.com/techtoolindia/)
[Facebook](https://facebook.com/techtoolindia/)