How to login in Laravel using Facebook account

Hi Guys,

In this tutorial, we will learn how to apply Facebook login in Laravel. We will follow simple steps for login with Facebook account in Laravel. if you have login with social in your application, it becomes awesome for your users. It increase the users on application, so if you want to apply login with Facebook below steps will help you. Follow the below steps for login with Facebook.

  1. Install Laravel

First you have to install Laravel in your machine using following command.

composer create-project laravel/laravel fblogin

2. Install Laravel Jetstream with the following command.

composer require laravel/Jetstream

3. Run npm install

npm install

4. Run Dev Package

npm run dev

5. Install socialite package

composer require laravel/socialite

6 Add Providers and Alias in config/app.php

'providers' => [
     Laravel\Socialite\SocialiteServiceProvider::class,

],

'aliases' => [
     'Socialite' => Laravel\Socialite\Facades\Socialite::class,
    ],

7. Add new column to the users table “fb_id”

php artisan make:migration add_fb_id_column_in_users_table --table=users –-create

8 Open the migration file and add below script  

database\migrations\timestamp_add_fb_id_column_in_users_table.php

<?php

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

class AddFbIdColumnInUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('fb_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('fb_id');
        });
    }
}

9. Create Database and set DB credentials in .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=fbtest
DB_USERNAME=root
DB_PASSWORD=

11. run the migrate command.

php artisan migrate

12. Install Jetstream livewire

php artisan jetstream:install livewire

13.Set following code in user model 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 string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'fb_id'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast.
     *
     * @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',
    ];
}

13 Enter App ID and App Secret in the config/service.php.

'facebook' => [
        'client_id' => 'Add you client id',
        'client_secret' => 'Add client secret',
        'redirect' => 'http://localhost:8000/auth/facebook/callback',
    ],

14 Create a controller

php artisan make:controller FbLoginController

15. Add below functions in controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;
use Validator;
use Socialite;
use Exception;
use Auth;

use App\Services\SocialFacebookAccountService;
class FbLoginController extends Controller
{
    public function facebookRedirect()
    {
        return Socialite::driver('facebook')->redirect();
    }

    public function loginWithFacebook()
    {
        try {
    
            $user = Socialite::driver('facebook')->user();
            $isUser = User::where('fb_id', $user->id)->first();
            if($isUser){
                Auth::login($isUser);
                return redirect('http://localhost:8000/');
            }else{
                $createUser = User::create([
                    'name' => $user->name."Test",
                    'email' => $user->email,
                    'fb_id' => $user->id,
                    'password' => encrypt('user@123')
                ]);
    
                Auth::login($createUser);
                return redirect('http://localhost:8000/');
            }
    
        } catch (Exception $exception) {
            dd($exception->getMessage());
        }
    }
}

16 Create route

use \App\Http\Controllers\FbLoginController;

Route::get('auth/facebook', [FbLoginController::class, 'facebookRedirect']);
Route::get('auth/facebook/callback', [FbLoginController::class, 'loginWithFacebook']);

17 Add Login button in view page

<a class="btn" href="{{ url('auth/facebook') }}"
style="background: #3B5499; color: #ffffff; padding: 10px; width: 100%; text-align: center; display: block; border-radius:2px;">
Login with Facebook
</a>

18. Run your application

php artisan serve

Complete Code:

https://github.com/blogshub4/How-to-login-in-Laravel-using-Facebook-account

One thought on “How to login in Laravel using Facebook account

Leave a Reply

Your email address will not be published. Required fields are marked *