Laravel 5.7 Facebook Login Tutorial Step by Step

Generic placeholder image
Brijpal Sharma
laravel  

Date:-October 08th, 2018 , Posted On:- Web Development


Laravel 5.7 Facebook Login Tutorial Step by Step is today topic, we learn how to users log in with facebook in Laravel 5.7.

Today we learn how to user login with facebook in Laravel 5.7  and store user login detail in the database. we will learn in this blog how to integrate Facebook socialite login in Laravel 5.7 application.

Step:1 Create a new project for Laravel Facebook Login

First, create a new Laravel 5.7 project following this is a command.

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

Go to that project folder and start the Laravel server using the following command.

php artisan serve

you can see your Laravel 5.7 Facebook Login project live on this  URL: http://localhost:8000

first, we are going to configure your database in the .env file.

Laravel 5.7 comes with by default two tables. So we can run the following command to migrate table.

php artisan migrate

You can see two table password_reset and users migrated in the MySQL database.

Step 2: Create Laravel Authentication

Laravel provides us with a basic authentication system. Laravel 5.7 makes authentication very simple. In fact, almost everything is already configured as email verification in Laravel 5.7. We just need to enter one command in our terminal, and then we ready to go.

php artisan make:auth

After that, you can see the updated route file with auth Routes. Now you see the login and registration dashboard.

Step: 3 Download Laravel/Socialite package for Laravel 5.7 Facebook Login Tutorial

The socialite is a full package that makes building authentification system with traditional social networks simple. install Laravel.Socialite using this command.

composer require laravel/socialite

Now, we add some code to config/app.php the file.

<?php

// app.php

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

    Laravel\Socialite\SocialiteServiceProvider::class,
],

And, also update an alias.

<?php

// app.php

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

Step:4 To Get Tokens Create a Facebook App 

First, Go to Facebook’s developers URL: https://developers.facebook.com/  and log in with your Facebook account.

After that, you can see Facebook developers Dashboard. now there is Create App button. So click that button and you will see this page.

 

Facebook dashboard

After filling name and email. you will see this dashboard.

Laravel 5.7 Facebook Login Tutorial Step by Step

You can see your App ID on the dashboard.

Now we select the Facebook Login option from the above options. after that, you can see this dashboard here we select the platform for these apps.

Laravel 5.7 Facebook Login Tutorial Step by Step

After select any platform, you need to register your domain name you will get your App ID and App Secret, which we use in our Laravel application.

App ID: xxxxxxxxx
App Secret: xxxxxxx

Now, copy both of them and switch to your Laravel application.

Navigate to the config\services.php file and write one another services array by the following code.

<?php

// services.php

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

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

Step:5 Create Controller for Laravel Facebook login

Create a new controller for Laravel facebook login.

php artisan make:controller SocialAuthFacebookController

In this controller add two function redirect() function to redirect the user to Facebook and callback() function is used for handle user when callback from facebook.

<?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, we are going to add the route to web.php.

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

After that go to the config->services.php and add some facebook key array with clients _id, clients_secret key and redirection URL.

<?php

// services.php

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

Step:6 Create Login view file with the blade.

Now we are going to add facebook login link in resources >views > auth >  login.blade.php and add one link.

@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 Start your Laravel serve using this command

php artisan serve

Now Create a Model for the Social login account.

If you try to login with facebook you will redirect nothing. let's fix it.

 php artisan make:model SocialFacebookAccount -m

After that add some table column in create_social_facebook_accounts_table.php

 <?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 to refresh if you have migrated previous tables.

php artisan migrate:refresh

If you did not migrate table before then run this command.

php artisan migrate

Step:7 Make a Relations to SocialFacebookAccount model

Now, Add relations and make fillable to the  SocialFacebookAthe ccount the 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);
  }
}

In the next step, we are going to handle service. this service use to register the user or login if the user already exists. create a folder in app/Services. 

Laravel 5.7 has not any service folder in app directory so we are manually creating a new folder and add page SocialFacebookAccountService.php.

appS/ervices/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;
        }
    }
}

This service finds provider account in the system and if it is not available it will create a new user. this method will also use try to associate the social media accounts.

Now our application is ready to handle facebook callback function.

Step:8 Update callback function

Update callback() function in SocialAuthFacebookController.php.

<?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');
    }
}

Now, this is the final code of this login with facebook in Laravel 5.7 Application.

Now we try to login with facebook and after login facebook redirect on the home page.

Step:9 Make user Application live

STEP 1:

go to the login page of Facebook Developer -> Your App

In Settings -> Basic -> Contact Email. (Give your 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? 

choose  "Yes"

And now your app will be live. Now, you will be able to log in as any other Facebook user account.

 

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

So here complete our tutorial Laravel-5-7-facebook-login-tutorial-step-by-step.

 


About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

6 comments
Generic placeholder image
Juan Pablo
March 13th, 2019 - 3:42AM

Thanks a lot, i test with Laravel 5.8 and work perfecto. Only one change. In app/Http/Controllers/SocialAuthFacebookController.php i add ->stateless() method in Socialite() public function callback(SocialFacebookAccountService $service) { $user = $service->createOrGetUser(Socialite::driver('facebook')->stateless()->user()); auth()->login($user); return redirect()->to('/home'); }

Generic placeholder image
Brijpal Sharma
March 13th, 2019 - 2:53PM

Thanks Juan Pablo

Generic placeholder image
Lara
March 27th, 2019 - 9:09PM

Hello I have a problem after click login with facebook cURL error 77: error setting certificate verify locations: CAfile: C:\xampp\apache\bin\curl-ca-bundle.crt CApath: none (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) Can you help me why show to me this error

Generic placeholder image
Lara
March 28th, 2019 - 1:43AM

Please do you sent me your soruce code complety

Generic placeholder image
prc
August 08th, 2019 - 5:38AM

I am getting error when i am using this code and error is Class "App\Http\Controllers\SocialFacebookAccountService does not exist" please help me out

Generic placeholder image
Brijpal Sharma
September 16th, 2019 - 3:14PM

PRC you need to create a controller "SocialFacebookAccountService"

You must be logged in to post a comment.