Laravel 9 Socialite Login with Facebook Tutorial

10-Apr-2023

.

Admin

Laravel 9 Socialite Login with Facebook Tutorial

Hello Friends,

Today, I will explain to you the step-by-step login with facebook account in laravel 9 using socialite. laravel 9 socialite provide api to login with facebook account. you can easily login using facebook account in laravel 9 application.

As we know social media is become more and more popular in the world. everyone has a social account like facebook, google, linkedin, twitter, etc. I think also most have a facebook account. So if your application has a login with social then it become awesome. you got more people to connect with your website because most people do not want to fill sign up or sign in form. If their login with social then it become awesome.

So if you want to also implement login with facebook account then I will help you with step-by-step instruction. let's follow the tutorial and implement it.

Step 1: Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

Step 2: Database Configuration

In the second step, we will make database Configuration for the example database name, username, password, etc. So let's open the .env file and fill in all details like as below:

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=here your database name(blog)

DB_USERNAME=here database username(root)

DB_PASSWORD=here database password(root)

Step 3 : Install Jetstream

Here we need auth scaffolding of jetstream. i will give full example for how to install jetstream so click here.

Step 4: Install Socialite

In this step, we need laravel/socialite package. you can install the socialite package using the below command so let's run the below command :

composer require laravel/socialite

After install above package you can add providers and aliases in the config file, Now open the config/app.php file and add the service provider and alias.

config/app.php

....

'providers' => [

....

Laravel\Socialite\SocialiteServiceProvider::class,

],

'aliases' => [

....

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

],

....

Step 5: Add Facebook App

In this step, we need a facebook app id and a secret that way we can get information from other users. so if you don't have facebook app account then you can create from here : https://developers.facebook.com/apps and after create account you can copy client id and secret.

Now you have to set app id, secret, and call back url in the config file so open config/services.php and set id and secret this way:

config/services.php

return [

....

'facebook' => [

'client_id' => 'app id',

'client_secret' => 'add secret',

'redirect' => 'http://localhost:8000/auth/facebook/callback',

],

]

Step 6: Add Database Column

In this step first we have to create migration for add facebook_id in your user table. So let's run bellow command:

php artisan make:migration add_facebook_id_column_in_users_table --table=users

database/migrations/2020_09_18_052105_add_facebook_id_column_in_users_table.php

<?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()

{

Schema::table('users', function ($table) {

$table->dropColumn('facebook_id');

});

}

}

Update mode like this way:

app/Models/User.php

<?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',

'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',

];

/**

* Write code on Method

*

* @return response()

*/

public function addNew($input)

{

$check = static::where('facebook_id',$input['facebook_id'])->first();

if(is_null($check)){

return static::create($input);

}

return $check;

}

}

Step 7: Add Routes

Here, we need to add a resource route for login with facebook account. so open your "routes/web.php" file and add the following route.

routes/web.php

<?php

use App\Http\Controllers\Auth\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']);

Step 8: Add Controller

php artisan make:controller FacebookController

After add the route, we need to add a method of facebook auth that method will handle facebook callback url and etc, first put the below code on your FacebookController.php file

app/Http/Controllers/Auth/FacebookController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\User;

use Validator;

use Socialite;

use Auth;

use Exception;

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('/dashboard');

}else{

$newUser = User::create([

'name' => $user->name,

'email' => $user->email,

'facebook_id'=> $user->id,

'password' => encrypt('123456dummy')

]);

Auth::login($newUser);

return redirect('/dashboard');

}

} catch (Exception $e) {

dd($e->getMessage());

}

}

}

Step 9: Update Blade File

Ok, now at last we need to add blade 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>

<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>

Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/login

You will see layout as like bellow:

Output :

It will help you...

#Laravel 9