Laravel 8 Socialite Login with Facebook Account Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hi Developer’s,
Hope all are feelings good.Here today, i will give you a example of how to works laravel 8 login with facebook account. I will show you Laravel 8 Socialite Login. On this post I will give you a very simple  and short example of laravel 8 login with any facebook account. I explained it very simply about laravel 8 jetstream login with facebook account. Now on this tutorial I will give you a short and simple example of login with facebook in laravel 8 application.

As we know now a days social media is a become more and more popular everywhere in the world. Everyone have social account as like gmail, facebook etc. I think also most of we have facebook account. So if in our application have a login with our social then it become awesome. You will get more people connect with our website. Because most we do not want to fill up any sign up or sign in form. If there have login system with social network than it become more awesome.So Laravel 8 Socialite Login is good for our applications.

So if we want to also implement our login with our facebook account then here i will help you step by step instruction. let’s start and follow tutorial and implement it.

Step 1: Install Laravel 8

This is our first step. On in this step, if you have no laravel 8 application on your pc then setup. Then we have to get fresh laravel 8 application by run bellow command and to get clean and fresh laravel 8 application.

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

Read Also: How to Send Mail in Laravel 8 using Mailtrap?

Step 2: Install JetStream

That’s good. Now, in this step, we need to use composer command to install jetstream package. So let’s run bellow command and install bellow package in your application.

composer require laravel/jetstream

Now, next we need to create a authentication using bellow command. By using that you can create basic login, register and email verification. If you also want to create team management then you need to pass a addition parameter. You can use bellow commands:

php artisan jetstream:install livewire

Now, let’s run node js package:

npm install


let’s run new package:

npm run dev

Now, we have to run migration command to create new database table:

php artisan migrate

Step 3: Install Socialite

In nex step i will install Socialite Package that provide us api to connect with facebook account. So, now open our terminal and fire bellow command:

composer require laravel/socialite


Step 4: Create Facebook App

Now we have to go https://developers.facebook.com site and need to create app for facebook login client id and secret id. After the create new account we can copy client id and secret id.

Now we need to set our app id, secret key and also call back url in config file . So open config/services.php and set id and secret key this way:

config/services.php

return [
    ....
    'facebook' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://localhost:8000/auth/facebook/callback',
    ],
]

Step 4: Add Database Column

Now in this step first we have to create a migration for add new facebook_id in our users table. So now let’s run bellow command:

php artisan make:migration add_facebook_id_column

Migration

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class AddFacebookIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('facebook_id')->nullable();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

Read Also: How to get current date time in vue js?

Update mode like this way:

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;
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',
        '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',
    ];
}

Step 5: Create Routes

So after adding facebook_id column on database table first we need to add new route for facebook login on our application. So let’s add bellow route in our routes.php file.

app/Http/routes.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FacebookController;
  
/*
|--------------------------------------------------------------------------
| 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', [FacebookController::class, 'redirectToFacebook']);
Route::get('auth/facebook/callback', [FacebookController::class, 'handleFacebookCallback']);

Read Also: Get Checked Radio Button Value in Vue JS

Step 6: Create Controller

After the successfully add route, we just need to add method for facebook auth that method will handle facebook callback url and etc. Now we need to put bellow code on ourFacebookController.php file.

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('dashboard');
         
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'facebook_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('dashboard');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}


Step 7: Update Blade File

Ok that’s good, now we are at last step.on this step we need to add blade file for view. So first create new file login.blade.php file and put bellow code:

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 value="Email" />
                <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>
  
            <div class="mt-4">
                <x-jet-label value="Password" />
                <x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>
  
            <div class="block mt-4">
                <label class="flex items-center">
                    <input 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('auth/facebook') }}" style="margin-top: 0px !important;background: blue;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>

Read Also : How to Get Selected Option Text in Vue JS ?

Ok wow, now we are fully ready to use open your browser and check here: URL + ‘/login’.

I hope it can help you…

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →