Laravel 9 Socialite Login with Facebook Account

Websolutionstuff | Apr-16-2022 | Categories : Laravel PHP

In this article, we will see laravel 9 socialite login with a facebook account. Many websites provide different types of login authentication to users like login with facebook, login with google/email, login with Github, and login with Twitter.

So, let's see login with facebook in laravel 9, laravel 9 jetstream login with facebook, facebook API, laravel/socialite facebook, login with facebook account in laravel 9 socialite, laravel 9 socialite facebook login.

Here I have used laravel 9 jetstream authentication for laravel social login example.

Step 1: Install Laravel 9 for Socialite Login with Facebook Account

Step 2: Install JetStream for Laravel Authentication

Step 3: Install Socialite Package

Step 4: Create Facebook App

Step 5: Changes in Config File

Step 6: Create Controller for Facebook Login

Step 7: Create Route

Step 8: Add Code in Blade File

Step 9: Add Column in Database

Step 10: Update Model

Step 11: Run Project

 

Step 1: Install Laravel 9 for Socialite Login with Facebook Account

In this step, we will install laravel 9 using the below command.

composer create-project --prefer-dist laravel/laravel laravel_9_login_with_facebook

 

 

Step 2: Install JetStream for Laravel Authentication

In this step, we will install jetstream. So, run the below command.

composer require laravel/jetstream

Now, we need to install livewire using the below command and also we need basic authentication like login and registration otherwise you can install using auth command.

php artisan jetstream:install livewire

Now, Install npm and run the package.

npm install
npm run dev

 Now, we will create a database using the migration command.

php artisan migrate

 

Step 3: Install Socialite Package

 Now, we will install the socialite package which provides API to connect with a facebook account.

composer require laravel/socialite

 

 

Step 4: Create Facebook App

In this step, Login in Facebook developer account. And create an app like the below image.

laravel_9_socialite_login_with_facebook_account_app_create

Now, Goto Facebook Settings and add your callback/redirect URL in Valid OAuth Redirect URL Save it as the below image.

laravel_9_socialite_login_with_facebook_account_add_products

Now, we required a Facebook client id and secret key, if you don't have a Facebook app account then you need to create one from the below link.

 

 

Create Facebook Account after creating an account you can copy the client id and secret key.

laravel_9_socialite_login_with_facebook_account_app_and_secret_key

 

Step 5: Changes in Config File

Now, we will set the client id, secret key, and call back URL in the config file. So, open the config/services.php file and add id and secret key.

<?php
return [
    'facebook' => [
        'client_id' => 'your client ID',
        'client_secret' => 'your client secret',
        'redirect' => 'http://localhost:8000/callback',
    ],
];

 

Step 6: Create Controller

Now, create a controller. And we have added redirect() function to redirect the user to Facebook and callback() function is used for handle user when callback from Facebook.

<?php

namespace App\Http\Controllers;

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

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

    public function facebookCallback()
    {
        try {
        
            $user = Socialite::driver('facebook')->user();
         
            $finduser = User::where('facebook_id', $user->id)->first();
        
            if($finduser){
         
                Auth::login($finduser);
        
                return redirect()->intended('dashboard');
         
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'facebook_id'=> $user->id,
                    'password' => encrypt('Test123456')
                ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('dashboard');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

 

 

Step 7: Create Route

In this step, we will add the below code to your route file.

<?php

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

Route::get('/redirect', [LoginWithFacebookController::class, 'redirectFacebook']);
Route::get('/callback', [LoginWithFacebookController::class, 'facebookCallback']);

 

Step 8: Add Code in Blade File

 Now, Add the below code in resources/views/auth/login.blade.php.

<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>
            <div class="flex items-center justify-end mt-4">
                <a class="ml-1 btn btn-primary" href="{{ url('redirect') }}" style="margin-top: 0px !important;background: #4c6ef5;color: #ffffff;padding: 5px;border-radius:7px;" id="btn-fblogin">
                    <i class="fa fa-facebook-square" aria-hidden="true"></i> Login with Facebook
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

 

 

Step 9: Add Column in Database

In this step, add a column in the user table and set the name as facebook_id.

php artisan make:migration Add_Facebook_Id_To_Users

Now, add a new column in your code like the below code.

 public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('facebook_id')->nullable();
        });
    }

 

Step 10: Update Model

Now, Update the model as below.

<?php

namespace App\Models;

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\Jetstream\HasTeams;
use Laravel\Sanctum\HasApiTokens;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','facebook_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',
    ];
}

 

 

Output:

laravel_9_socialite_login_with_facebook_account

 


You might also like :

Recommended Post
Featured Post
How To Install Python On Ubuntu
How To Install Python On Ubunt...

In this article, we will see how to install python on ubuntu. Python is a popular programming language. P...

Read More

May-06-2022

How to Create Trait in Laravel 10 Example
How to Create Trait in Laravel...

Hello developers! 👋 Today, let's dive into the wonderful world of Laravel 10 and explore one of its handy featu...

Read More

Feb-09-2024

Laravel AJAX CRUD example
Laravel AJAX CRUD example

Today I will show you how to create ajax crud operations in laravel. In laravel 6/7 ajax crud operation, we can perform...

Read More

May-14-2020

How To Image Upload With Preview In Angular 15
How To Image Upload With Previ...

In today's world of web development, being able to upload images with a preview feature is a common requirement for...

Read More

Jun-16-2023