Facebook login using laravel

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.

https://developers.facebook.com/apps/create
1. Choose any types of app and give the name of app.
2. Choose facebook login and click setup
3. https://developers.facebook.com/apps/215728518272049/settings/basic/ ( Get client id and client secret )
4. https://developers.facebook.com/apps/215728518272049/fb-login/settings/  (add redirect url here )
.env

FACEBOOK_CLIENT_ID = 215728518272049
FACEBOOK_CLIENT_SECRET = c0870ccaead069be5da181404fb09801
composer require laravel/socialite
config/app.php

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

'aliases' => [
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
config/services.php

'facebook' => [
   'client_id' => env('FACEBOOK_CLIENT_ID'),
   'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
   'redirect' => 'https://ecommerce.factpoll.com/callback/redirect',
],
Route::get('/auth/facebook-login', [ServiceController::class, 'facebook_login'])->name('facebook_login');
Route::get('/callback/redirect', [ServiceController::class, 'facebook_login_redirect'])->name('facebook_login_redirect');
use Laravel\Socialite\Facades\Socialite;

function facebook_login(Request $req){ return Socialite::driver('facebook')->redirect(); }
function facebook_login_redirect(Request $req){

try{

$user = Socialite::driver('facebook')->user();
$findUser = User::where('email', $user->email)->first();

if(!$findUser){
User::create([
'name' => $user->name, 
'email' => $user->email,
'password' => Hash::make($user->email) 
]);

if(Auth::attempt(['email' => $user->email, 'password' => $user->email])){ 
Auth::login($findUser ); 
return redirect('dashboard')->withSuccess('You have successfully registered & logged in!'); 
}
}
else{
if(Auth::attempt(['email' => $user->email, 'password' => $user->email])){ 
Auth::login($user );  
return redirect('dashboard')->withSuccess('You have successfully registered & logged in!'); 
}

}
}
catch(Exception $e){
dd($e->getMessage());
}


}

Leave a Reply