Login with facebook in laravel using socialite

721 0 0 0

Last Updated : 2024-04-26 21:01:10

In this snippet I am going to explain how to login to your system with facebook using laravel socialite package

There are alot of steps you hav to do to login with facebook using socailite


step 1 (facebook developer)


Go to facebook developer website (https://developers.facebook.com/) and login with your facebook account -> from the header -> choose My Apps -> then choose create App button -> fill all the details required and create the app .


Afo to the app created -> from sidebar -> choose settings -> choose basic -> copy your app ID and secret (we wil need them later).


step 2 (install socialite)


install laravel socialite package using composer like this


composer require laravel/socialite

NOTE: If Using Laravel lower than version 8 Include Package in Providers in config/app.php like this


Laravel\Socialite\SocialiteServiceProvider::class,
// Scroll Down to aliases section and add below code
'Socialite' => Laravel\Socialite\Facades\Socialite::class,

step 3 (include facebook service)


Include facebook service in config/services.php file


'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => 'http://yourWebsite.com/callback-url', // for example http://localhost/yourwebsite/public/facebook/callback/
],

And at the .env file include your facebook app ID and Secret


#Facebook login API
FACEBOOK_CLIENT_ID= // App Id here
FACEBOOK_CLIENT_SECRET= // App Secret here

step 4 (create controller & add facebook routes)


At this stage you have to create a new controller to handle facebook methos (or using existing controller)


php artisan make:controller FacebookController

Add facebook routes in routes file


Route::prefix('facebook')->as('facebook.')->group(function () {
Route::get("/auth", ['uses'=>'FacebookController@loginUsingFacebook', 'as'=>'login']);
Route::get("/callback", ['uses'=>'FacebookController@callbackFromFacebook', 'as'=>'callback']);
});

In the facebook controller you have to provide 2 methods (one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication) to handle login process


<?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; // Don't forget to include socialite

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

public function callbackFromFacebook() {
try {
$user = Socialite::driver('facebook')->user();

// Check Users Email If Already There
$is_user = User::where('email', $user->getEmail())->first();
if(!$is_user){

$saveUser = User::updateOrCreate([
'linkedin_id' => $user->getId(),
],[
'name' => $user->getName(),
'email' => $user->getEmail(),
'password' => Hash::make($user->getName().'@'.$user->getId())
]);
}else{
$saveUser = User::where('email', $user->getEmail())->update([
'linkedin_id' => $user->getId(),
]);
$saveUser = User::where('email', $user->getEmail())->first();
}

Auth::loginUsingId($saveUser->id);

return redirect()->route('homePageRoute');
} catch (\Throwable $th) {
throw $th;
}
}


}

step 5 (Add facebook login button)


now you have to provide login with facebook button in login page you want


<a href="{{ route('facebook.login') }}" class="btn btn-primary">
<i class="fab fa-facebook-f fa-fw"></i>
Login with Facebook
</a>

step 6 (add facebook_id to users table through migrations)


Now you have to add facebook_id column to users table through a migration file, so let's create the migration file


php artisan make:migration add_facebook_id_in_users_table

at the migration we created add this code


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

then run migrate command


php artisan migrate

step 7 (Update user model fillable)


Now it's time to update the user model fillable in models/User.php file with adding facebook_id column to it


protected $fillable = [
'name',
'email',
'password',
'facebook_id'
];

Finally you have to go to login page and try login with facebook button, it will work perfectly.


GOOD LUCK


 

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.