DEV Community

Cover image for How to Login with facebook in Laravel 8 ?
shani singh
shani singh

Posted on • Edited on

3 1

How to Login with facebook in Laravel 8 ?

In this post i am going to explain about Laravel Socialite Authentication using Facebook.

To Start with follow the below steps.

STEP 1

Install Laravel Socialite Package using composer.



composer require laravel/socialite


Enter fullscreen mode Exit fullscreen mode

NOTE: If Using Laravel lower than version 8 Include Package in Providers.
In config/app.php file add the below provider



Laravel\Socialite\SocialiteServiceProvider::class,


Enter fullscreen mode Exit fullscreen mode

Scroll Down to aliases section and add below code



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


Enter fullscreen mode Exit fullscreen mode

Step 2

Include Facebook Service in config/services.php file.



'facebook' => [
        'client_id' => '', //USE FROM FACEBOOK DEVELOPER ACCOUNT
        'client_secret' => '', //USE FROM FACEBOOK DEVELOPER ACCOUNT
        'redirect' => 'https://examplelaravel8.test/facebook/callback/'
    ],


Enter fullscreen mode Exit fullscreen mode

STEP 3

Here, you have to create Facebook app so that you can get a client_id and client_secret from Facebook.

You can do this by going to Facebook’s developers URL

and log in with your Facebook account.

Go to My Apps, proceed to Add New App

STEP 4

Create a new controller to handle socialite action. Run below command to generate a new controller



php artisan make:controller FaceBookController


Enter fullscreen mode Exit fullscreen mode

Update FacebookController With Code Below Which have 2 Function To Redirect and To 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;
       }
   }
}


Enter fullscreen mode Exit fullscreen mode

STEP 5

Add Facebook authentication routes



// Facebook Login URL
Route::prefix('facebook')->name('facebook.')->group( function(){
    Route::get('auth', [FaceBookController::class, 'loginUsingFacebook'])->name('login');
    Route::get('callback', [FaceBookController::class, 'callbackFromFacebook'])->name('callback');
});


Enter fullscreen mode Exit fullscreen mode

STEP 6

ADD Facebook Button on Login Page resources/views/auth/login.blade.php



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


Enter fullscreen mode Exit fullscreen mode

STEP 7

Add facebook_id Column in Users table, create a migration be command below



php artisan make:migration add_facebook_id_in_users_table


Enter fullscreen mode Exit fullscreen mode

Add Below Code in Migration file



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


Enter fullscreen mode Exit fullscreen mode

and run migration



php artisan migrate


Enter fullscreen mode Exit fullscreen mode

STEP 8

Update The User Model Fillable Property in Models/User.php



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


Enter fullscreen mode Exit fullscreen mode

Finally Go To Login Page And Try Accessing Login With Facebook Button.

Facebook Login

If you get any issue while integrating it, do comment your problems.

Get Code on Techtool Github

You can watch this video I have explained this.

Thank You for Reading

Reach Out To me.
Twitter
Instagram
YouTube

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (2)

Collapse
 
shakilahmed01 profile image
Shakil Ahmed • Edited

i am getting this kind of error after all
dev-to-uploads.s3.amazonaws.com/up...

Collapse
 
lum3ll_96 profile image
Luca Mellano

Yes, they forgot to add controller in the route web file:

use App\Http\Controllers\FaceBookController

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay