Laravel 8 Socialite Login with Facebook Account Example
Hi Dev,
Here, i will show you how to works laravel 8 login with facebook. This post will give you simple example of laravel 8 login with facebook account. i explained simply about laravel 8 jetstream login with facebook. This tutorial will give you simple example of login with facebook in laravel 8.
As we know social media is a become more and more popular in the world. every one have social account like gmail, facebook etc. i think also most of have facebook account. So if in your application have login with social then it become awesome. you got more people connect with your website because most of people does not want to fill sign up or sign in form. If there login with social than it become awesome.
So if you want to also implement login with facebook account then i will help you step by step instruction. let's follow tutorial and implement it.
Preview:
Step 1: Install Laravel 8
In this step, if you haven't laravel 8 application setup then we have to get fresh laravel 8 application. So run bellow command and get clean fresh laravel 8 application.
composer create-project --prefer-dist laravel/laravel facebookLogin
Step 2: Install JetStream
Now, in this step, we need to use composer command to install jetstream, so let's run bellow command and install bellow library.
composer require laravel/jetstream
now, we need to create authentication using bellow command. you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. you can see bellow commands:
php artisan jetstream:install livewire
Now, let's node js package:
npm install
let's run package:
npm run dev
now, we need to run migration command to create database table:
php artisan migrate
Step 3: Install Socialite
In first step we will install Socialite Package that provide api to connect with facebook account. So, first open your terminal and run bellow command:
composer require laravel/socialite
Step 4: Create Facebook App
You have to go https://developers.facebook.com and create app for facebook login client id and secret.after create account you can copy client id and secret.
Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:
config/services.php
return [
....
'facebook' => [
'client_id' => 'app id',
'client_secret' => 'add secret',
'redirect' => 'http://localhost:8000/auth/facebook/callback',
],
]
Step 4: Add Database Column
In this step first we have to create migration for add facebook_id in your user table. So let's run bellow command:
php artisan make:migration add_facebook_id_column
Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddFacebookIdColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function ($table) {
$table->string('facebook_id')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
Update mode like this way:
app/Models/User.php
<?php
namespace App\Models;
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',
'facebook_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',
];
}
Step 5: Create Routes
After adding facebook_id column first we have to add new route for facebook login. so let's add bellow route in routes.php file.
app/Http/routes.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FacebookController;
/*
|--------------------------------------------------------------------------
| 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', [FacebookController::class, 'redirectToFacebook']);
Route::get('auth/facebook/callback', [FacebookController::class, 'handleFacebookCallback']);
Step 6: Create Controller
After add route, we need to add method of facebook auth that method will handle facebook callback url and etc, first put bellow code on your FacebookController.php file.
app/Http/Controllers/FacebookController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class FacebookController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function redirectToFacebook()
{
return Socialite::driver('facebook')->redirect();
}
/**
* Create a new controller instance.
*
* @return void
*/
public function handleFacebookCallback()
{
try {
$user = Socialite::driver('facebook')->user();
$finduser = User::where('facebook_id', $user->id)->first();
if($finduser){
Auth::login($finduser);
return redirect()->intended('dashboard');
}else{
$newUser = User::create([
'name' => $user->name,
'email' => $user->email,
'facebook_id'=> $user->id,
'password' => encrypt('123456dummy')
]);
Auth::login($newUser);
return redirect()->intended('dashboard');
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
}
Step 7: Update Blade File
Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:
resources/views/auth/login.blade.php
<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 value="Email" />
<x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
</div>
<div class="mt-4">
<x-jet-label value="Password" />
<x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
</div>
<div class="block mt-4">
<label class="flex items-center">
<input 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>
<div class="flex items-center justify-end mt-4">
<a class="ml-1 btn btn-primary" href="{{ url('auth/facebook') }}" style="margin-top: 0px !important;background: blue;color: #ffffff;padding: 5px;border-radius:7px;" id="btn-fblogin">
<i class="fa fa-facebook-square" aria-hidden="true"></i> Login with Facebook
</a>
</div>
</form>
</x-jet-authentication-card>
</x-guest-layout>
Ok, now you are ready to use open your browser and check here : URL + '/login'.
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 8 Inertia JS CRUD with Jetstream & Tailwind CSS
- Laravel 8 Yajra Datatables Example Tutorial
- Laravel 8 Import Export Excel and CSV File Tutorial
- Laravel 8 Livewire CRUD with Jetstream & Tailwind CSS
- Laravel 8 Mail | Laravel 8 Send Email Tutorial
- Laravel 8 PDF | Laravel 8 Generate PDF File using DomPDF
- Laravel 8 Auth with Inertia JS Jetstream Tutorial
- Laravel 8 Auth with Livewire Jetstream Tutorial
- Laravel 8 Authentication using Jetstream Example
- Laravel 8 CRUD Application Tutorial for Beginners
- Laravel 8/7/6 Google ReCAPTCHA Form Validation Example