Laravel 9 - Login with Facebook using Socialite
Laravel 9 - Login with Facebook using Socialite
In this tutorial, we will discuss how to use the Socialite package to log in with Facebook in Laravel 9. Socialite is a package that simplifies OAuth authentication with popular social media platforms like Facebook, Google, and GitHub, allowing users to log in via these platforms while handling the authentication process seamlessly.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
In this guide, you’ll integrate Facebook login into a Laravel project using the Socialite package. After creating a new Laravel project and setting up a MySQL database, you’ll install UI authentication and add necessary fields to the users table. The Socialite package will be installed and configured to allow Facebook authentication. A SocialController will be created to handle the redirect and callback, and routes will be set up accordingly. Finally, you’ll update the login blade with a Facebook login button and test the integration.
Step # 1 : Create Fresh Laravel Project.
If the Laravel Installer is globally installed, use the command below to create a project named facebook
laravel new facebook
Or use
If the Laravel Installer is not globally installed, use Composer to create the project named facebook
composer create-project laravel/laravel --prefer-dist facebook
Step # 2 : Create a Database.
Create a new database named facebook in your database management tool (phpMyAdmin), then open the .env file in your Laravel project and update the database configuration with the details of your new database.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=facebook
DB_USERNAME="your database username"
DB_PASSWORD="your database password"
Step # 3 : Let's install UI authentication.
Install UI authentication, generate the UI auth scaffolding, install the necessary NPM dependencies, and compile the frontend assets using Laravel Mix with the following commands.
composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev
Step # 4 : Add field to users table.
Add a new field fb_id to the users table by accessing the create_users_table migration. Update the migration to include the fb_id field and assign it as fillable in the User model.
$table->id();
$table->string('fb_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
Assign fb_id as a fillable property in the User model.
protected $fillable = [
'fb_id',
'name',
'email',
'password',
];
Run the migration to apply changes.
php artisan migrate
Step # 5 : Install Socialite package.
Install the Socialite package, which is required for integrating social authentication with services like Facebook, using the below command.
composer require laravel/socialite
Step # 6 : Register socialite package (Optional)
Register the Socialite package by adding it to the providers and aliases arrays in the config/app.php file (this step is optional in Laravel 8 and beyond)
'providers' => [
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
Step # 7 : Get facebook app_id and app_secret.
Get your Facebook app_id and app_secret by logging into Meta for Developers at (Link : https://developers.facebook.com/). Then, access the config/services.php file and add your Facebook credentials to the facebook configuration array.
Access config/services.
'facebook' => [
'client_id' => 'Your facebook app id',
'client_secret' => 'Your facebook/meta secret',
'redirect' => 'http://localhost:8080/auth/facebook/callback', //Your redirect call back. In my case i am using port 8080. If you are using port 8000 or if you are not using any port you need to update url accordingly
],
Step # 8 : Create SocialController.
Create a new controller named SocialController using the following command.
php artisan make:controller SocialController
Update the SocialController with the following code.
<?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')->stateless()->user();
$existingUser = User::where('fb_id', $user->id)->first();
if($existingUser){
Auth::login($existingUser);
return redirect('/home');
}else{
$createUser = User::create([
'name' => $user->name,
'email' => $user->email,
'fb_id' => $user->id,
'password' => encrypt('password')
]);
Auth::login($createUser);
return redirect('/home');
}
} catch (\Throwable $th) {
throw $th;
}
}
}
Step # 9 : Setup routes.
Setup routes for Facebook authentication by adding the following to your routes/web.php.
Route::get('auth/facebook', 'App\Http\Controllers\SocialController@facebookRedirect');
Route::get('auth/facebook/callback', 'App\Http\Controllers\SocialController@loginWithFacebook');
Step # 10 : Add Facebook login href to your Login/Register blade.
Add the Facebook login link to your Login/Register blade by including the following inside the form in your resources/views/auth/login.blade.php or register.blade.php.
<div class="row mb-3">
<label for="password" class="col-md-4 col-form-label text-md-end"></label>
<div class="col-md-6">
<a class="btn btn-primary" href="{{ url('auth/facebook') }}"> Login with Facebook</a>
</div>
</div>
Step # 11 : It's time to test.
Run the following command to start your Laravel development server and access the Login/Register page.
php artisan serve
Now you should be able to login using Facebook.
Conclusion
By following the steps, you’ll enable Facebook login in your Laravel app. The process involves configuring the Socialite package, setting up necessary routes, and integrating the Facebook login button into the frontend. Once complete, users will be able to authenticate using their Facebook credentials, and their information will be saved in the database for future use.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments