Here is the step-by-step guide to creating a login system in the laravel app using Facebook using the Socialite package:
Step 1: Installing Laravel 11
You can use the below command to install the new Laravel project:
composer create-project --prefer-dist laravel/laravel facebooklogin
Go inside the project folder:
cd facebooklogin
Step 2: Configure the database
Add a database configuration to the .env file like this:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=8889 DB_DATABASE=facebooklogin DB_USERNAME=root DB_PASSWORD=root
Step 3: Install Jetstream
To install Jetstream in Laravel, use the below command:
composer require laravel/jetstream
After installing, you need to publish Jetstream’s assets.
php artisan jetstream:install livewire
It will install some libraries and create tables and some configurations.
Step 4: Install the socialite package
The Socialite is an exceptional package for creating a Social OAuth 2.0 Authentication in Laravel.
Install the package using the below command:
composer require laravel/socialite
Step 5: Setup Developer Application on Facebook
To signin our Laravel application through the Facebook app, we need to create a developer application on Facebook.
To create a developer application, Go to the Facebook for Developers portal.
You can log in through this portal using “Regular Facebook credentials”.
And you will see this page and now click on the “My apps” navigation item.
And you will see this screen like this:
After creating an application, you will need to authenticate and request data from users with Facebook Login like this:
Here, we are adding a usecase for the Facebook application to authenticate and request data from users with Facebook login.
Since we are not creating a Facebook app for building a game, we are creating a Facebook login, so select the “No, I am not building a game” option.
Let’s go to the next step.
Here, you need to provide an App name and App contact email. After filling in the details, click the “Create app” button.
After creating an app, go to the “Use cases” navigation item. Then click on the “Customize” button under “Authentication and account creation.”
Let’s customize the use case and add the permission to read the user email like this:
After adding an email permission, go to the settings page, which will show the “OAuth setting page” like this:
Now, our last step is to collect the App ID and secret.
To get the App ID and secret, you need to navigate to App Setting >> Basic tab, and you will see your credentials like this:
We will grab these credentials and redirect_uri and add them to the .env file like this:
FACEBOOK_APP_ID=[your_id] FACEBOOK_CLIENT_SECRET=[your_key] REDIRECT_URI=http://localhost:8000/facebook/callback
Now, open the config/services.php file and add the below configurations:
'facebook' => [ 'client_id' => env('FACEBOOK_APP_ID'), 'client_secret' => env('FACEBOOK_CLIENT_SECRET'), 'redirect' => env('REDIRECT_URI'), ],
Step 6: Modify the users table
Modify the existing users table in the database by adding a “facebook_id” column.
php artisan make:migration add_facebook_id_to_users
Add a column like this:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('users', function (Blueprint $table) { $table->string('facebook_id')->after('remember_token')->nullable()->unique(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('users', function (Blueprint $table) { $table->dropColumn('facebook_id'); }); } };
Run this migration to add a column to the users table:
php artisan migrate
Step 7: Add a facebook_id to the User.model file
In the User.php model file, you must add facebook_id to the $fillable property.
<?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<int, string> */ protected $fillable = [ 'name', 'email', 'password', 'facebook_id' ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', 'two_factor_recovery_codes', 'two_factor_secret', ]; /** * The accessors to append to the model's array form. * * @var array<int, string> */ protected $appends = [ 'profile_photo_url', ]; /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; } }
Step 8: Create a FacebookController
To create a controller, use this command:
php artisan make:controller FacebookController
This FacebookController.php will have two basic functions:
- redirectToFacebook(): This will redirect to the Facebook app for authentication.
- handleFacebookCallback(): This will call back to our app after successful authentication.
Here is the complete code for FacebookController.php file:
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; use Laravel\Socialite\Facades\Socialite; use Throwable; class FacebookController extends Controller { /** * Redirect to Facebook for authentication. * * @return RedirectResponse */ public function redirectToFacebook(): RedirectResponse { return Socialite::driver('facebook')->redirect(); } /** * Handle Facebook authentication callback. * * @return RedirectResponse */ public function handleFacebookCallback(): RedirectResponse { try { $facebookUser = Socialite::driver('facebook')->user(); } catch (Throwable $e) { return redirect()->route('login')->with('error', 'Facebook authentication failed.'); } // Retrieve user from the database by facebook_id or create a new user $user = User::firstOrCreate( ['facebook_id' => $facebookUser->id], [ 'name' => $facebookUser->name, 'email' => $facebookUser->email, 'password' => Hash::make(Str::random(16)) ] ); // Login the user Auth::login($user, true); // Remember the user return redirect()->intended('dashboard'); } }
Step 9: Register the routes
Add the below code inside the routes/web.php file:
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\FacebookController; Route::get('/', function () { return view('welcome'); }); Route::middleware([ 'auth:sanctum', config('jetstream.auth_session'), 'verified', ])->group(function () { Route::get('/dashboard', function () { return view('dashboard'); })->name('dashboard'); }); Route::controller(FacebookController::class)->group(function () { Route::get('facebook/redirect', 'redirectToFacebook')->name('auth.facebook'); Route::get('facebook/callback', 'handleFacebookCallback'); });
Step 10: Add the login link to the login.blade.php file
Update your resources/views/auth/login.blade.php file to add the “Login with Facebook” button.
<x-guest-layout> <x-authentication-card> <x-slot name="logo"> <x-authentication-card-logo /> </x-slot> <x-validation-errors class="mb-4" /> @session('status') <div class="mb-4 font-medium text-sm text-green-600"> {{ $value }} </div> @endsession <form method="POST" action="{{ route('login') }}"> @csrf <div> <x-label for="email" value="{{ __('Email') }}" /> <x-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus autocomplete="username" /> </div> <div class="mt-4"> <x-label for="password" value="{{ __('Password') }}" /> <x-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" /> </div> <div class="flex mt-4 justify-between"> <a href="{{ route('auth.facebook') }}" style="padding: 10px 20px; background-color: #1DA1F2; color: white; text-decoration: none; border-radius: 5px; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.2); transition: background-color 0.3s ease;"> Login with Facebook </a> </div> <div class="block mt-4"> <label for="remember_me" class="flex items-center"> <x-checkbox id="remember_me" name="remember" /> <span class="ms-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 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" href="{{ route('password.request') }}"> {{ __('Forgot your password?') }} </a> @endif <x-button class="ms-4"> {{ __('Log in') }} </x-button> </div> </form> </x-authentication-card> </x-guest-layout>
Save this file and now go to this URL: http://localhost:8000/login
Now, click on the “Login with Facebook” button, and you will be redirected to Facebook put in your username and password, and you will be redirected to the Laravel app as a logged-in user, and your URL will be like this: http://localhost:8000/dashboard
That’s it! We successfully logged in through Facebook in our Laravel application.
Here is the complete code on Github
Gabriel Marquez
Nice post, It works fully, I followed step by step. However, it just works for the facebook account you set up on the dashboard of facebook developer. If I want to log in with another account, it doesn’t work fully.
Krunal
Okay, go to your development account and make the app live and then again try to logged in as another user.
Gabriel Marquez
The step 10 works properly. Do you know if making your app and all its live features available to the general public wont have any security problems?
Krunal
Nope, you just need to assign proper permissions required by the application and also there are so many different algorithms which you can secure your app, but some of them, you need to develop on your own.
FredFlinstone
hi,
very thanks for this great tutorial … everything is working fine, but … if I login via FB, user XY is logged into web, then I log out successfully. Meanwhile I check db-table “users” and user XY is added to db-table (name, email, password, remember_token).
Then I try log as XY in via credentials – email/password, but error message is raised (These credentials do not match our records.)
What is wrong? because this credential really exists in db-table “users”.
Muhammad Akbar
Because you generated random password in the service, either you need the user to create a new password or keep using the facebook login
Yogi Sadhewo
hi krunal, your tutorial was amazing. i have followed step by step, but i dont know why i can’t log in, the command says “These credentials do not match our records.”. i hope you read my comments and help me out once again thank you 😀
jc
Class App\Http\Controllers\SocialFacebookAccountService does not exist
Son Nguyen
Make sure you have this in file SocialAuthFacebookController.php
use App\Services\SocialFacebookAccountService;
Roslan Ramli
still in the controller $service is undefined
Roslan Ramli
I am using laravel 5.6
use App\Services\SocialFacebookAccountService; was pasted and not used:
$service not defined
Roslan Ramli
Sorry my bad, I forgot to inject $service
Abhishek jain
Good post. Working properly… Thumbs up
wlad
I followed the steps until 6 there I got an error window that says: URL LOCKED: An error occurred in the redirect because the url is not included … To what is this and what can I do. Thank you
kyamasam
Awesome tutorial. Works as expected on a live server. Not tried it on local server though.
Sarwan
I clone your code from github and use on localhost follow your instructions but I got error Can’t load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.
How I can sort this issue
Krunal
You need to create an app in your facebook developer account.
Sarwan
Thanks sir for reply.
I sort previous issue.I have another issue when i using different facebook user then creating issue given below:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column ’email’ cannot be null (SQL: insert into `users` (`email`, `name`, `password`, `updated_at`, `created_at`) values (, Sarwan Pal, 23fa71cc32babb7b91130824466d25a5, 2018-02-09 07:20:40, 2018-02-09 07:20:40))
but when i using facebook app generated by id then i not facing issue given above.
Sarwan
Please reply sir
If I want to log in with another account, it doesn’t work fully.
somur ruteeb
Nice work,
I did this in my website, but the weakness that if the user uses the mobile to login via facebook, he well redirect to facebook on broweser not the facebook app. Is there any idea if i can redirect to facebook app intead of broswer ??
ajay
sir it is not return email i dont know what happen
it is return name but not email i cant reach this problem please help me
Saha
Hi, Many many thanks for this good tutorial. Everything is working fine .. But Now I want these randomly generate password send to user through his email. Now what can I do ?
nico
Everything worked functionally except when it redirects me back to my site im still not logged in,
Ghaith
Nice guide, this however can’t be tested longer as facebook now refuse authentication from a non https source. it is not possible to disable any new apps force https option. Any work around?
Thanks for the help.
Nandini
I got this error
Insecure Login Blocked: You can’t get an access token or log in to this app from an insecure page. Try re-loading the page as https://
Please help me.
fahmi
hye,did u know how to retrieve picture from socialite (fb/google) and make it as profile picture in laravel?
saqib khan
Hello Kunal,
Thank you for such an elaborated and made easy tutorial. It works all fine. But When I try to login with facebook ot gives error “You are not logged in: You are not logged in. Please log in and try again.”
And if I manually am logged in then it gives error about invalid access or something. In short it is not logging in from website. Please help.
Thanks
veerapandian
I got this error
Insecure Login Blocked: You can’t get an access token or log in to this app from an insecure page. Try re-loading the page as https://
How can i solve this?
Fen
It works on my site. However, google gives me an error about callback url:
——————————————————–
URL:
https://dance.zhengfen.ch/callback
Error details
Linked from
Last crawled: 4/25/18
First detected: 4/24/18
Googlebot couldn’t access the contents of this URL because the server had an internal error when trying to process the request. These errors tend to be with the server itself, not with the request. More info.
————————————-
How to avoid this? maybe change the method of the url ?
Route::get(‘/callback’, ‘AuthFacebookController@callback’);
-> Route::post’/callback’, ‘AuthFacebookController@callback’);
surabhi
Thank You,very helpful post.
Fredrik
Very nice guide! I wouldn’t use md5(rand(1,10000)) for passwords, though, a password like that can be brute-forced in less than 10000 attempts. Use md5(random_bytes(64)) instead.
Jacek Chałupka
Great tutorial, thank You very much.
I just would like to ask a question, as I am new to Laravel. Why did You put creating or getting user in service not in controller itself? Just so the controller code would be clearer or is there another reason?
sayeed roshan
Awesome tutorial. Works fine for me,
Facing only one challenge, if i am in either in cart or any other page page after login it should redirect to the particular page. How can I achieve this, Please help me
Ronie Meque
Amazing tutorial. I’m usually lazy to comment thanking, but this time I just had to. Thanks!!!
Roslan Ramli
I am getting error from this line from the controller
$service is undefined
Roslan Ramli
Sorry, my bad, I forgot to inject $service
Roslan Ramli
Your instructions and code are good. Thanks, manage to deploy on a new live digitalocean host.
However on my development env, I am using ubuntu on windows and set one of the hosts as dev.company.biz. So I manage to get laravel with ‘php artisan serve’landing page on dev.company.biz.
So, is it possible on the callback to return to dev.company.biz
Roslan Ramli
How do I get facebook’s avatar into the database. Please help me cause I just cannot proceed, since I have tried it since morning. I tried adding the below code to SocialFacbookAccountService.php
$user = User::create([
’email’ => $providerUser->getEmail(),
‘name’ => $providerUser->getName(),
‘password’ => md5(rand(1,10000)),
‘avatar’ => $providerUser->getAvatar() // added code
]);
but I get null in the database.
Julian
Nice posts! works really well
demet Akyol
Hello ,I have a question.
If the user is not registered, we are generating a random password and the user how to know use this password at the next login.
swati
login with only one email ..how we login with another email??
Kishan Paneri
I got error like this
Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
Pat
Whats the best way to add twitter into this setup. I have facebook up and working now but would like to extend it
Gaurav
help me to resolve this issue, i have done everything, installed certificates and all.
still its giving same error..
Insecure login blocked: You can’t get an access token or log in to this app from an insecure page. Try re-loading the page as https://
gaurav
help me to resolve this issue, i have done everything, installed certificates and all.
still its giving same error..
Insecure login blocked: You can’t get an access token or log in to this app from an insecure page. Try re-loading the page as https://
Shahid Hussain
How can i sove this issue login to facebook in laravel app
Insecure Login Blocked: You can’t get an access token or log in to this app from an insecure page. Try re-loading the page as
i have setup facebook login/setting/oauth redirect URI to but still an error
Rogério Aguiar Hanssen
Hi, i’m using Laravel 5.7 and I’m getting an error that user_id can’t be null when trying to create SocialFacebookAccount. Regards.
Roger Silva Santos Aguiar
Hello! I followed step by step, but when I try to login with facebook, I have the following error:
SQLSTATE[42703]: Undefined column: 7 ERROR: column “id” does not exist LINE 1: …t”, “created_at”) values ($1, $2, $3, $4, $5) returning “id” ^ (SQL: insert into “social_facebook_accounts” (“provider_user_id”, “provider”, “user_id”, “updated_at”, “created_at”) values (2161413204171060, facebook, 1, 2019-03-08 15:26:57, 2019-03-08 15:26:57) returning “id”)
Previous exceptions
SQLSTATE[42703]: Undefined column: 7 ERROR: column “id” does not exist LINE 1: …t”, “created_at”) values ($1, $2, $3, $4, $5) returning “id” ^ (42703)
I checked my code, it is everything equal your code, can you help me please?
Priyanka
Hi,
Amazing tutorial… I have integrated your code in my applications and its working great. However, when the user is redirected back from Facebook callback url it doesn’t show the user as logged in to the application. The user is redirected to the homepage but restricted pages that should only be visible to authenticated users are not displayed here. Any guesses what should i do?
Thanks
souvik
site url is not there in facebook developer
David Blackwell
Hi, thanks for your great tutorial.
It works well, I am happy with your tutorial.
I have just one question, if I am going to integrate this Facebook login with mobile app, what should I do in API side?
Happy coding,
Regards.
jasbir singh
Amazing tutorial, i set up facebook login in just one hour.
Thanks author
Ruchita Puri
Hi,
I implement the above code same as it is. The difference is that i install laravel version 6.3 instead of 5.4.
But i am getting error.
When i click on “login with facebook” button, it goes to http://localhost:8000/callback?code=randomstring&state=randomstring. on this page it shows error like “Laravel\Socialite\Two\InvalidStateException”.
I tried: config/session.php change ‘domain’ => env(‘SESSION_DOMAIN’, null), to ‘domain’ => env(‘SESSION_DOMAIN’, ‘http://localhost:8000/’).
Still not worked for me. please tell me what is the issue ASAP
Ishrat Ali
how to do facebook login with laravel api?
스보벳
I’m very pleased to uncover this page. I need
to to thank you for your time for this particularly wonderful read!!
I definitely appreciated every part of it and i also have you saved to fav to see new information on your
blog.