How to use Facebook to log into a Laravel application. If you have the same query, keep reading; in this article, we'll learn how to use the Socialite package in Laravel to log in with a Facebook social media account.
The Laravel Socialite package allows you to create a strong, expressive OAuth authentication interface with a variety of social media networks, including Facebook, Twitter, Google, LinkedIn, GitHub, GitLab, and Bitbucket.
Its user-centric boilerplate social authentication technique saves you time.
Logging in with social accounts is a simple process that improves the user experience; nowadays, everyone understands that a better user experience is critical to the success of any digital product.
The user's anticipation to access and register within the application is pushed ahead by social login.
As a result, we're adding a simple Facebook login capability to the Laravel application. For this lesson, we'll need authentication user interface templates, and we'll be utilizing Laravel Jetstream to automate the process.
Laravel Jetstream is a well created authentication scaffolding built using Tailwind CSS; you can also use Livewire or Inertia scaffolding to create auth templates.
It supports Laravel by providing login, registration, email verification, two-factor authentication, session management, and API support. Incredible, isn?t it?
Let?s start integrating Login with Facebook in the Laravel application.
1. Set Up Laravel Environment
composer create-project laravel/laravel --prefer-dist laravel-socialite-login-facebook-example
Take a look inside the project:
cd laravel-socialite-login-facebook-example
2. Add Database Details
Enter the database name, user name, and password for your database in the.env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=
3. Setting up Jetstream in Laravel
Jetstream may be installed with the following command:
composer require laravel/jetstream
Execute command to generate authentication templates such as login, register and email verification.
php artisan jetstream:install livewire
Next, run below command.
npm install
Using the node package manager, run dev packages.
npm run dev
To migrate authentication properties, run the command.
php artisan migrate
4. Install Socialite Package in Laravel
With the following line, you can install the socialite package in Laravel.
composer require laravel/socialite
Register the socialite plugin in the providers and aliases array in config/app.php
.
....
....
'providers' => [
....
....
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
....
....
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
....
....
5. Add Facebook ID in Users Table
We need to keep adding the Facebook id to the users table.
php artisan make:migration add_fb_id_column_in_users_table --table=users
Go to the newly generated file.
migrations/timestamp_add_fb_id_column_in_users_table.php file, add the fb_id column value.
<?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');
});
}
}
Also, in the app/Models/User.php section, add the Facebook ID table value.
<?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',
'fb_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',
];
}
6. Add Facebook App ID and Secret
To log in using Facebook, you must first develop a Facebook app, which you may do by visiting Facebook Developer.
Register in the config/services
file after creating a Facebook app id and a secret app.
return [
....
....
....
'facebook' => [
'client_id' => 'Facebook app id',
'client_secret' => 'Facebook add secret',
'redirect' => 'http://localhost:8000/auth/facebook/callback',
],
]
7. Generate and Configure Controller
Create a new controller after that.
php artisan make:controller SocialController
Place the following code in app/Http/Controllers/SocialController.php.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Validator;
use Socialite;
use Exception;
use Auth;
class SocialController 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('/dashboard');
}else{
$createUser = User::create([
'name' => $user->name,
'email' => $user->email,
'fb_id' => $user->id,
'password' => encrypt('admin@123')
]);
Auth::login($createUser);
return redirect('/dashboard');
}
} catch (Exception $exception) {
dd($exception->getMessage());
}
}
}
8. Setting Up Route
Define the routes in the routes/web.php file.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SocialController;
/*
|--------------------------------------------------------------------------
| 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', [SocialController::class, 'facebookRedirect']);
Route::get('auth/facebook/callback', [SocialController::class, 'loginWithFacebook']);
9. Add Login with Facebook Button in Login View
Add the following code to the views/auth/login.blade.php file to add the Login with Facebook button to the Login view template.
<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 for="email" value="{{ __('Email') }}" />
<x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')"
required autofocus />
</div>
<div class="mt-4">
<x-jet-label for="password" value="{{ __('Password') }}" />
<x-jet-input id="password" class="block mt-1 w-full" type="password" name="password" required
autocomplete="current-password" />
</div>
<div class="block mt-4">
<label for="remember_me" class="flex items-center">
<input id="remember_me" 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>
</div>
{{-- Login with Facebook --}}
<div class="flex items-center justify-end mt-4">
<a class="btn" href="{{ url('auth/facebook') }}"
style="background: #3B5499; color: #ffffff; padding: 10px; width: 100%; text-align: center; display: block; border-radius:3px;">
Login with Facebook
</a>
</div>
</form>
</x-jet-authentication-card>
</x-guest-layout>
Begin using the app.
php artisan serve
Use the following URL to see how far you've progressed:
http://127.0.0.1:8000/login
The Laravel Login with Facebook tutorial is now complete.
As a result, we demonstrated how to connect with Facebook in the Laravel app; however, the Socialite package also allows you to login with Twitter, Google, LinkedIn, GitHub, GitLab, and Bitbucket.
We also demonstrated how to quickly create an authentication UI in Laravel using Laravel Jetstream.
I hope you will like the content and it will help you to learn Laravel 9 Socialite Login with Facebook Tutorial
If you like this content, do share.