Laravel Socialite Authentication with Facebook using Laravel 8

 Laravel Socialite Authentication with Facebook using Laravel 8



  • Let us develop a sample web project to integrate Facebook login.
  • First of all create a sample Laravel project using below command. If you want to know how to config Laravel in your PC please refer my blog about "First step to Laravel".
        composer create-project laravel/laravel <your project name>

  • Next we should install the Laravel Socialite Package using the composer. Note that you have to include Package in Providers if you are using below version than Laravel 8
        composer require laravel/socialite

  • Add below code to config\app.php in providers section
        Laravel\Socialite\SocialiteServiceProvider::class,

  • Add below code to in aliases section
        'Socialite' => Laravel\Socialite\Facades\Socialite::class,

  • To config\services.php include Facebook service
        'facebook' => [
        'client_id' => '', //USE FROM FACEBOOK DEVELOPER ACCOUNT
        'client_secret' => '', //USE FROM FACEBOOK DEVELOPER ACCOUNT
        'redirect' => 'https://examplelaravel8.test/facebook/callback/'
        ],

  • In order to get the client id and client secret you have to login with your Facebook account create a developer account in https://developers.facebook.com/
  • Next, create a new app. After creating the new app it will generate the client id and client service

  • Create a controller 
        php artisan make:controller FaceBookController

  • We have to write functions for Redirect and handle Callback

        <?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;
       }
   }
}

  • Create routes in web.php

    // Facebook Login URL
Route::prefix('facebook')->name('facebook.')->group( function(){
    Route::get('auth', [App\Http\Controllers\FaceBookController::class, 'loginUsingFacebook'])->name('login');
    Route::get('callback', [App\Http\Controllers\FaceBookController::class, 'callbackFromFacebook'])->name('callback');
});
  • Add the users id column for the Users table
        php artisan make:migration add_facebook_id_in_users_table

  • Add below to the migration add_facebook_id_in_users_table file

<?php

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

class AddFacebookIdInUsersTable extends Migration
{
    /**
     * 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');
        });
    }
}

  • Run the migration
        php artisan migrate

  • Update the fillable property in Users model
        protected $fillable = [
        'name',
        'email',
        'password',
        'status',
        'facebook_id'
        ];

  • Now run the application and check to login with Facebook
        php artisan serve

  • Good job!!!

Comments

Popular posts from this blog

Load balance with NGINX

First Step to Laravel

Send Email through Laravel