Laravel Facebook Login: How to Use Facebook Login in Laravel

55
3685
Laravel Facebook Login

I will show you how to log in users with Facebook and save them into your database using Laravel. ThenI will guide you on integrating Facebook socialite login into your Laravel application. So let us start.

Step 1: Make a project of  Laravel Facebook Login.

Create a Laravel project by typing the following command.

composer create-project laravel/laravel socialLogin --prefer-dist

Go to that project and start the Laravel server by typing the following command.

php artisan serve

The server starts at URL: http://localhost:8000.

You need to configure your database in a .env file.

Laravel ships with, by default, two tables. So run the following command in your terminal after setting up the database.

php artisan migrate

Two tables of users and password_reset tables and one migration table generated in MySQL Database

Step 2: Create a Laravel Authentication

Laravel Auth

Laravel provides us with basic authentication. Furthermore, laravel makes implementing authentication very simple. Almost everything is configured for you out of the box. We need to fire one command in our terminal, and we are ready to go.

php artisan make:auth

You can see in the terminal that Authentication scaffolding was generated successfully.

If we switch to the routes >> web.php file, then there is one added route, and our view is configured automatically.

<?php 

// web.php

Auth::routes();

Change to this URL: http://localhost:8000/login

You can see something like this, and yes, don’t forget to start the server all the time by firing the command php artisan serve.

Laravel 5.4 Socialite Facebook Login

 

Step 3: Download the laravel/socialite package for laravel Facebook integration.

The socialite is a package that makes building authentification with traditional social networks simple. So we are using this Laravel specific package.

composer require laravel/socialite

Now, add the service provider to the config/app.phpfile.

<?php

// app.php

'providers' => [
    // Other service providers...

    Laravel\Socialite\SocialiteServiceProvider::class,
],

Moreover, also update an alias array.

<?php

// app.php

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

Step 4: Create Facebook App To Get Tokens

Go to Facebook’s developers portal by following URL: https://developers.facebook.com/.

Login via your Facebook account. You will see something like this.

Facebook Login

 

You can see in the image that there is Create App button. So click that button, and you will find one popup window like this.

Create New App ID

 

Here, I have put my name and email id in the popup and pressed the button of Create App ID.

You will see your dashboard like this.

Laravel 5 Facebook Login

 

In your dashboard, you can see your App ID.

Now we need to select the Facebook Login option from the above image. So click that button, and you will redirect to the Facebook Login Dashboard page. You can see your App ID and App Secret on this page, which we need in our Laravel Application.

App ID: xxxxxxxxx
App Secret: xxxxxxx

Now, grab both of them and switch to your editor.

Navigate to the config  >>  services.php file and put another services array by the following code.

Your App ID becomes your client_id, and App Secret becomes client_secret

<?php

// services.php

'facebook' => [
    'client_id' => 'xxxxxxx',
    'client_secret' => 'xxxxxxxx',
    'redirect' => '',
],

Possible Error: 

When you try to log in via Facebook, you will get the following error if you have not added the domain in your Facebook app.

Can’t load URL: The domain of this URL is not included in the app’s domains. To load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.

Possible Solution: 

You need to add the platform to your Facebook dashboard and, in that, type your project’s root URL like this.

Socialite Laravel 5 Facebook Login

 

Step 5: Generate a controller for Laravel Facebook Login.

We need to create one controller that handles the Facebook Authentication routes.

php artisan make:controller SocialAuthFacebookController

We need to implement two methods in this controller: the following.

1)redirect():  Redirect our users to Facebook.

2) callback():  Handle callback from Facebook.

<?php

// SocialAuthFacebookController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Socialite;

class SocialAuthFacebookController extends Controller
{
  /**
   * Create a redirect method to facebook api.
   *
   * @return void
   */
    public function redirect()
    {
        return Socialite::driver('facebook')->redirect();
    }

    /**
     * Return a callback method from facebook api.
     *
     * @return callback URL from facebook
     */
    public function callback()
    {
       
    }
}

The next step is going to the routes >> web.php file and registering the routes.

<?php

//web.php

/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/redirect', 'SocialAuthFacebookController@redirect');
Route::get('/callback', 'SocialAuthFacebookController@callback');

Route::get('/home', 'HomeController@index')->name('home');

Go to the config  >>  services.php file and update the Facebook keyed array with another key called redirect and put the value ‘http://localhost:8000/callback’

<?php

// services.php

'facebook' => [
    'client_id' => 'xxxxxxx',
    'client_secret' => 'xxxxxxx',
    'redirect' => 'http://localhost:8000/callback',
],

Step 6: Create a Login view file with Blade templating engine.

We need to add the link to our routeredirect to redirect the user to Facebook. So go to the resources  >>  views  >>  auth  >>  login.blade.php and add one link like Login with Facebook.

<!-- login.blade.php -->

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Login</div>
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="{{ route('login') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>

                                <a class="btn btn-link" href="{{ route('password.request') }}">
                                    Forgot Your Password?
                                </a>
                            </div>
                        </div>
                        <br />
                        <p style="margin-left:265px">OR</p>
                        <br />
                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                              <a href="{{url('/redirect')}}" class="btn btn-primary">Login with Facebook</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, if you have not started the server, then launch the server and go to the following URL

http://localhost:8000/login

Try to log in via Facebook and see if everything is set up correctly.

Possible Error:

cURL error 60: SSL certificate problem: unable to get local issuer certificate

Possible Solution: 

Assuming On Windows

XAMPP server

Similar to another environment – download and extract for cacert.pem here (a clean file format/data)

https://curl.haxx.se/docs/caextract.html  put it here

C:\xampp\php\extras\ssl\cacert.pem in your php.ini put this line in this section (“c:\xampp\php\php.ini”):

;;;;;;;;;;;;;;;;;;;;
; php.ini Options  ;
;;;;;;;;;;;;;;;;;;;;

curl.cainfo = "C:\xampp\php\extras\ssl\cacert.pem"

Moreover, finally, restart your server.

Step 7: Make one model for Social Account.

Now, when you try to Log in with Facebook, you will redirect to nothing, and in your URL, you can see the callback with some code in it. So let’s fix that.

Now, we are integrating our Facebook users into our Laravel application. Create one model as well as one migration in our app.

 php artisan make:model SocialFacebookAccount -m

Now, add the following code in the create_social_facebook_accounts_table.php file. I am putting my final file in here.

<?php

// create_social_facebook_accounts.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSocialFacebookAccountsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('social_facebook_accounts', function (Blueprint $table) {
          $table->integer('user_id');
          $table->string('provider_user_id');
          $table->string('provider');
          $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('social_facebook_accounts');
    }
}

Run the following command if you have migrated previous tables.

php artisan migrate:refresh

Alternatively, if this is your first-time migration, apply the following command.

php artisan migrate

Step 8: Give relations to the SocialFacebookAccount model.

The column is Facebook’s user id, and inprovider this case, it will always be Facebook.

Add relations and fillable to the  SocialFacebookAccount model.

<?php

// SocialFacebookAccount.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SocialFacebookAccount extends Model
{
  protected $fillable = ['user_id', 'provider_user_id', 'provider'];

  public function user()
  {
      return $this->belongsTo(User::class);
  }
}

The next step would be some handling service that will register the user or login if the account exists. Create folderapp/Services.

Laravel has no Services folder in the app directory, so create a directory first and put the following content in that SocialFacebookAccountService.php file. So our full directory structure would look like this.

app  >>  Services >> SocialFacebookAccountService.php

<?php

namespace App\Services;
use App\SocialFacebookAccount;
use App\User;
use Laravel\Socialite\Contracts\User as ProviderUser;

class SocialFacebookAccountService
{
    public function createOrGetUser(ProviderUser $providerUser)
    {
        $account = SocialFacebookAccount::whereProvider('facebook')
            ->whereProviderUserId($providerUser->getId())
            ->first();

        if ($account) {
            return $account->user;
        } else {

            $account = new SocialFacebookAccount([
                'provider_user_id' => $providerUser->getId(),
                'provider' => 'facebook'
            ]);

            $user = User::whereEmail($providerUser->getEmail())->first();

            if (!$user) {

                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName(),
                    'password' => md5(rand(1,10000)),
                ]);
            }

            $account->user()->associate($user);
            $account->save();

            return $user;
        }
    }
}

It will try to find the provider’s account in the system, and if it is not present, it will create a new user. This method will also try to associate the social account with the email address if the user already has an account.

Now everything is ready to handle Facebook’s callback to our app.

Step 9: Update callback function.

The last step is to update the SocialAuthFacebookController’s callback() function.

<?php

// SocialAuthFacebookController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Socialite;
use App\Services\SocialFacebookAccountService;

class SocialAuthFacebookController extends Controller
{
  /**
   * Create a redirect method to facebook api.
   *
   * @return void
   */
    public function redirect()
    {
        return Socialite::driver('facebook')->redirect();
    }

    /**
     * Return a callback method from facebook api.
     *
     * @return callback URL from facebook
     */
    public function callback(SocialFacebookAccountService $service)
    {
        $user = $service->createOrGetUser(Socialite::driver('facebook')->user());
        auth()->login($user);
        return redirect()->to('/home');
    }
}

All the coding is now finally complete. Next, go to the login URL of our application.

http://localhost:8000/login

Now, Login with Facebook, and you will redirect to the home page, and the data has been saved in the database.

login with facebook in laravel

Step 10: Make live your Laravel Facebook Integration with the public.

Your application is in development mode, so when you try to log in with another Facebook username and password, it will not work.

For that, you need to do following the steps.

STEP 1:

Log in to Facebook Developer -> Your App

In Settings -> Basic -> Contact Email. (Give any email)

STEP 2:

And in the ‘App Review’ Tab: change

Do you want to make this app and its live features available to the general public? Yes

And your app will be live now.

Now, you will be able to log in as any Facebook user.

Github: https://github.com/KrunalLathiya/LaravelFacebookLogin

Steps to use Github code

  1. Clone the repo in your local.
  2. Go to the project’s root and run the command “composer update.
  3. Edit the .env file and use your MySQL database credentials.
  4. Configure the developer’s Facebook account to get client_id and client_secret and put your Web URL.
  5. Run the command “php artisan migrate.
  6. We need to bootstrap the Laravel server, so run “php artisan serve.
  7. If now, go to this URL: http://localhost:8000/login.

55 Comments

  1. 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.

  2. 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?

    • 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.

  3. 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”.

    • Because you generated random password in the service, either you need the user to create a new password or keep using the facebook login

  4. 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 😀

  5. 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

  6. 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

  7. 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.

  8. 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 ??

  9. 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 ?

  10. 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.

  11. 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.

  12. 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

  13. 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?

  14. 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’);

  15. 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.

  16. 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?

  17. 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

  18. 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

  19. 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.

  20. 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.

  21. 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.

    • 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://

  22. 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://

  23. 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

  24. 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.

  25. 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?

  26. 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

  27. 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.

  28. 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

  29. 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.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.