In this tutorial, we are going to learn how to implement Facebook login using Socialite package in Laravel. When your users need to log to your application using their Facebook, this will be the easiest way to do it.

Prerequisites

  • Laravel
  • To Continue with this tutorial, you should have installed Laravel 8 in your pc. If you are still not installed Laravel in your machine you can configure it from here.

    Setting up the Project

    First you need to create a new laravel project by running below command in your terminal
    1
    composer create-project laravel/laravel laravel-socialite-facebook-login

    Then navigate to your project directory by using below command in your terminal

    1
    cd laravel-socialite-facebook-login

    Set up Database details

    Now you need to configure your Database details in your .env file.
    1
    2
    3
    4
    5
    6
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=laravel_socialite_facebook
    DB_USERNAME=root
    DB_PASSWORD=

    Setting up Jetstream in Laravel

    Install Jetstream by running below command.
    1
    composer require laravel/jetstream

    In here we are going to use default authentication templates given by Jetstream. To install that, you should run below command in your terminal.

    1
    php artisan jetstream:install livewire

    Then run below commands in you termial:

    1
    npm install && npm run dev

    Create Migration

    Now we need to add extra coumn to our default users_table_migration.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateUsersTable extends Migration
    {
    public function up()
    {
    Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('fb_id')->nullable();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
    });
    }

    public function down()
    {
    Schema::dropIfExists('users');
    }
    }

    Then we need to migrate our migration files by running below command in your terminal:

    1
    php artisan migrate

    Also don’t forget to Facebook ID table value in app/Models/User.php file.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    <?php

    namespace App\Models;

    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Fortify\TwoFactorAuthenticatable;
    use Laravel\Jetstream\HasProfilePhoto;
    use Laravel\Sanctum\HasApiTokens;

    class User extends Authenticatable
    {
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = [
    'name',
    'email',
    'password',
    'fb_id',
    ];

    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    protected $hidden = [
    'password',
    'remember_token',
    'two_factor_recovery_codes',
    'two_factor_secret',
    ];

    /**
    * The attributes that should be cast to native types.
    *
    * @var array
    */
    protected $casts = [
    'email_verified_at' => 'datetime',
    ];

    /**
    * The accessors to append to the model's array form.
    *
    * @var array
    */
    protected $appends = [
    'profile_photo_url',
    ];
    }

    Install Socialite Package

    Now we meed to install Socialite package in to our application.
    1
    composer require laravel/socialite

    Then you need to register Socialite package in our config/app.php file’s provider array and alias array:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    ....
    ....
    'providers' => [
    ....
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
    ],

    'aliases' => [
    ....
    ....
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
    ],
    ....
    ....

    Add Facebook App ID and Secret

    In order to login with Facebook, we need to create a Facebook app that you can do by going to Facebook Developer.

    After creating a Facebook app id and the secret app, register in the config/services file.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    return [
    ....
    ....
    ....
    'facebook' => [
    'client_id' => 'Facebook app id',
    'client_secret' => 'Facebook add secret',
    'redirect' => 'http://localhost:8000/auth/facebook/callback',
    ],
    ]

    Create Controller

    Next, generate a new controller.
    1
    php artisan make:controller SocialController

    Open app/Http/Controllers/SocialController.php and place the following code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    use App\Models\User;
    use Validator;
    use Socialite;
    use Exception;
    use Auth;

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

    public function loginWithFacebook()
    {
    try {

    $user = Socialite::driver('facebook')->user();
    $isUser = User::where('fb_id', $user->id)->first();

    if($isUser){
    Auth::login($isUser);
    return redirect('/dashboard');
    }else{
    $createUser = User::create([
    'name' => $user->name,
    'email' => $user->email,
    'fb_id' => $user->id,
    'password' => encrypt('admin@123')
    ]);

    Auth::login($createUser);
    return redirect('/dashboard');
    }

    } catch (Exception $exception) {
    dd($exception->getMessage());
    }
    }
    }

    Setting Up Route

    Open routes/web.php file and define the routes.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <?php

    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\SocialController;

    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */

    Route::get('auth/facebook', [SocialController::class, 'facebookRedirect']);

    Route::get('auth/facebook/callback', [SocialController::class, 'loginWithFacebook']);

    Add Login with Facebook Button in Login View

    Next, add Login with Facebook button in Login view template, so add the following code in views/auth/login.blade.php file.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    <x-guest-layout>
    <x-jet-authentication-card>
    <x-slot name="logo">
    <x-jet-authentication-card-logo />
    </x-slot>

    <x-jet-validation-errors class="mb-4" />

    @if (session('status'))
    <div class="mb-4 font-medium text-sm text-green-600">
    {{ session('status') }}
    </div>
    @endif

    <form method="POST" action="{{ route('login') }}">
    @csrf

    <div>
    <x-jet-label for="email" value="{{ __('Email') }}" />
    <x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')"
    required autofocus />
    </div>

    <div class="mt-4">
    <x-jet-label for="password" value="{{ __('Password') }}" />
    <x-jet-input id="password" class="block mt-1 w-full" type="password" name="password" required
    autocomplete="current-password" />
    </div>

    <div class="block mt-4">
    <label for="remember_me" class="flex items-center">
    <input id="remember_me" type="checkbox" class="form-checkbox" name="remember">
    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
    </label>
    </div>

    <div class="flex items-center justify-end mt-4">
    @if (Route::has('password.request'))
    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
    {{ __('Forgot your password?') }}
    </a>
    @endif

    <x-jet-button class="ml-4">
    {{ __('Login') }}
    </x-jet-button>
    </div>

    {{-- Login with Facebook --}}
    <div class="flex items-center justify-end mt-4">
    <a class="btn" href="{{ url('auth/facebook') }}"
    style="background: #3B5499; color: #ffffff; padding: 10px; width: 100%; text-align: center; display: block; border-radius:3px;">
    Login with Facebook
    </a>
    </div>
    </form>
    </x-jet-authentication-card>
    </x-guest-layout>

    Run the application

    To run your application run below command in your termial:
    1
    php artisan serve

    Then navigate to following URL:

    1
    http://127.0.0.1:8000/login

    Conclusion

    In this tutorial, we implemented password change functionality in Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail..