AppDividend
Latest Code Tutorials

Laravel 5 Facebook Login Tutorial

55

Laravel 5 Facebook Login Tutorial is the tutorial title today we will deep dive.  I am going to show you how to Login users with Facebook and save them into your database using Laravel 5.4 I will guide you how to Integrate Facebook socialite login into your Laravel 5.4 application. So let us start.

Step 1: Make a project of  Laravel Facebook Login.

Create a Laravel 5.4 project by typing following command.

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

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

php artisan serve

Server starts at URL: http://localhost:8000

You need to configure your database in .env file.

Laravel 5.4 ships with by default two tables. So run the following command in your terminal after setting up with 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 basic authentication. Laravel 5.4 makes implementing authentication very simple. In fact, almost everything is configured for you out of the box.  We just 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 generated successfully.

Now, if we switch to the routes >> web.php file then there is one added route, and also 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 command php artisan serve.

Laravel 5.4 Socialite Facebook Login

 

Step 3: Download the laravel/socialite package for laravel 5 facebook integration

Laravel 5 Facebook Login Tutorial

The socialite is a package that makes building authentification with traditional social networks simple. So we are using this Laravel 5.4 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 the 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 pop up window like this.

Create New App ID

 

Here, I have put my name and email id in the popup and press 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 Facebook Login option from above image. So click that button, and you will redirect to Facebook Login Dashboard page. In this page, you can see your App ID and App Secret, 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 one 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 login via facebook and if you have not added the domain in your Facebook app. You will get following error.

Can’t load URL: The domain of this URL is not 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.

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

Now, we need to create one controller, which handles the Facebook Authentication routes.

php artisan make:controller SocialAuthFacebookController

We need to implement two methods in this controller, which are following.

1)redirect():  Redirect our users to the 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()
    {
       
    }
}

Next step is going to the routes >> web.php file and register 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 Login view file with blade templating engine.

Now we just need to add the link to our routeredirect which will further redirect the user to the 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 the following URL

http://localhost:8000/login

Try to login via Facebook and if everything sets 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 user in 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 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, else, if this is your first-time migration then apply following command.

php artisan migrate

Step 8: Give relations to SocialFacebookAccount model.

The column provider_user_id is Facebook’s user id, and inprovider this case, 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);
  }
}

Next step would be some handling service that will try to register the user or login if the account already exists. Create folderapp/Services. Laravel 5.4 has not any Services folder in app directory so create a directory first and put 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 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 in case that 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. 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 5 Facebook Integration with the public.

Right now your application is in development mode, so when you try to login with another Facebook username and password then 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 ‘App Review‘ Tab: change

Do you want to make this app and all 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 root of the project and run command “composer update
  3. Edit .env file and use your MySQL database credentials.
  4. Configure developers facebook account get client_id and client_secret and also put your Web URL.
  5. Run the command “php artisan migrate
  6. Now, we need to bootstrap Laravel server so run “php artisan serve
  7. If now go to this URL: http://localhost:8000/login

If you still have doubt in this Laravel Facebook Login Tutorial, then ask in the comment below, I am happy to help you out.

55 Comments
  1. Gabriel Marquez says

    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.

    1. Krunal says

      Okay, go to your development account and make the app live and then again try to logged in as another user.

  2. Gabriel Marquez says

    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?

    1. Krunal says

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

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

    1. Muhammad Akbar says

      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. Yogi Sadhewo says

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

    Class App\Http\Controllers\SocialFacebookAccountService does not exist

    1. Son Nguyen says

      Make sure you have this in file SocialAuthFacebookController.php

      use App\Services\SocialFacebookAccountService;

      1. Roslan Ramli says

        still in the controller $service is undefined

      2. Roslan Ramli says

        I am using laravel 5.6
        use App\Services\SocialFacebookAccountService; was pasted and not used:
        $service not defined

        1. Roslan Ramli says

          Sorry my bad, I forgot to inject $service

  6. Abhishek jain says

    Good post. Working properly… Thumbs up

  7. wlad says

    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

  8. kyamasam says

    Awesome tutorial. Works as expected on a live server. Not tried it on local server though.

  9. Sarwan says

    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

    1. Krunal says

      You need to create an app in your facebook developer account.

  10. Sarwan says

    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.

  11. Sarwan says

    Please reply sir
    If I want to log in with another account, it doesn’t work fully.

  12. somur ruteeb says

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

  13. ajay says

    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

  14. Saha says

    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 ?

  15. nico says

    Everything worked functionally except when it redirects me back to my site im still not logged in,

  16. Ghaith says

    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.

  17. Nandini says

    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.

  18. fahmi says

    hye,did u know how to retrieve picture from socialite (fb/google) and make it as profile picture in laravel?

  19. saqib khan says

    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

  20. veerapandian says

    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?

  21. Fen says

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

  22. surabhi says

    Thank You,very helpful post.

  23. Fredrik says

    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.

  24. Jacek Chałupka says

    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?

  25. sayeed roshan says

    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

  26. Ronie Meque says

    Amazing tutorial. I’m usually lazy to comment thanking, but this time I just had to. Thanks!!!

  27. Roslan Ramli says

    I am getting error from this line from the controller
    $service is undefined

    1. Roslan Ramli says

      Sorry, my bad, I forgot to inject $service

  28. Roslan Ramli says

    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

  29. Roslan Ramli says

    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.

  30. Julian says

    Nice posts! works really well

  31. demet Akyol says

    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.

  32. swati says

    login with only one email ..how we login with another email??

  33. Kishan Paneri says

    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.

  34. Pat says

    Whats the best way to add twitter into this setup. I have facebook up and working now but would like to extend it

    1. Gaurav says

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

  35. gaurav says

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

  36. Shahid Hussain says

    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

  37. Rogério Aguiar Hanssen says

    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.

  38. Roger Silva Santos Aguiar says

    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?

  39. Priyanka says

    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

  40. souvik says

    site url is not there in facebook developer

  41. David Blackwell says

    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.

  42. jasbir singh says

    Amazing tutorial, i set up facebook login in just one hour.

    Thanks author

  43. Ruchita Puri says

    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

  44. Ishrat Ali says

    how to do facebook login with laravel api?

  45. 스보벳 says

    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

Your email address will not be published.

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