Laravel 11 Socialite Login with Facebook Account

Websolutionstuff | Aug-07-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to login with Facebook in laravel 11 Socialite. In laravel 11, we'll use Socialite to log in using Facebook. Here, we'll use laravel UI to login with a Facebook account.

Here, we'll create a login form and add the Facebook login button to that form.

Laravel 11 Socialite Login with Facebook Account

Laravel 11 Socialite Login with Facebook Account

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following command.

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

 

Step 2: Install Laravel UI

Next, we'll install Laravel UI using the following command.

composer require laravel/ui

Now, we need to create authentication using the below command. You can create a basic login, register, and perform email verification. We'll run the following commands to create a bootstrap auth scaffold:

php artisan ui bootstrap --auth

Now, let's node js package:

npm install

let's run the package:

npm run build

 

Step 3: Install Socialite

 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, go to 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 require 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 the id and secret key.

config/services.php

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

 

Step 6: Create Controller

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

app/Http/Controllers/FacebookController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
    
class FacebookController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToFacebook()
    {
        return Socialite::driver('facebook')->redirect();
    }
          
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleFacebookCallback()
    {
        try {
        
            $user = Socialite::driver('facebook')->user();
         
            $findUser = User::where('facebook_id', $user->id)->first();
         
            if($findUser){
         
                Auth::login($findUser);
        
                return redirect()->intended('home');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'facebook_id'=> $user->id,
                        'password' => encrypt('123456789')
                    ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('home');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

 

Step 7: Define Routes

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

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\FacebookController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
  
Route::controller(FacebookController::class)->group(function(){
    Route::get('auth/facebook', 'redirectToFacebook')->name('auth.facebook');
    Route::get('auth/facebook/callback', 'handleFacebookCallback');
});

 

Step 8: Update Blade File

Next, add the following HTML code to login file.

resources/views/auth/login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6 offset-md-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                    <label class="form-check-label" for="remember">
                                        {{ __('Remember Me') }}
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-6 offset-md-4 mt-2">
                                <a class="btn btn-primary" href="{{ route('auth.facebook') }}" style="display: block;">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 32 32">
                                        <path fill="#FFFFFF" d="M32 16.084c0-8.837-7.162-16-16-16S0 7.247 0 16.084c0 8.013 5.873 14.644 13.568 15.843v-11.22h-4.087v-4.623h4.087v-3.489c0-4.041 2.423-6.279 6.118-6.279 1.775 0 3.628.312 3.628.312v3.985h-2.046c-2.017 0-2.637 1.255-2.637 2.539v2.931h4.467l-.713 4.623h-3.754v11.22C26.127 30.728 32 24.097 32 16.084z"/>
                                    </svg>
                                    Login with Facebook
                                </a>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Step 9: Add a Column in the 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.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function ($table) {
            $table->string('facebook_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        //
    }
};

Now, Update the model as below.

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

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

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

 

Step 10: Run Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like :

Recommended Post
Featured Post
How To Integrate Paypal Payment Gateway In Laravel
How To Integrate Paypal Paymen...

In this tutorial I will teach you the most important topic of how to integrate the PayPal payment gateway in larave...

Read More

Jul-22-2020

Access Denied for user 'root'@'localhost' phpMyAdmin
Access Denied for user 'root'@...

phpMyAdmin is a valuable web-based tool for managing MySQL databases, simplifying various database tasks. However, runni...

Read More

Jul-28-2023

How to Disable Right Click using jQuery
How to Disable Right Click usi...

In this small post i will show you how to disable right click using jquery. Here, we will disable right click on pa...

Read More

Aug-18-2021

How to Create Bar Chart in Vue 3 using vue-chartjs
How to Create Bar Chart in Vue...

Hello, web developers! In this article, we'll see how to create a bar chart in vue 3 using vue-chartjs. Here, w...

Read More

Jul-31-2024