Laravel

Laravel Login with Facebook with SDK javascript

Login with Facebook with SDK javascript

At this time many people do not want to remember passwords for every website, So almost all websites require login with Facebook or Google. Today I will show you step by step, how to implement a Facebook login on your website. If you want to implement Login with Facebook with SDK on your website follow the below-given steps.

Step-1 Setup Facebook developer account

First, log into your Facebook developer account click here, and click on the Create app button.

When clicking on the Create App button show a new page for select app type and click next.

Now you fill in your basic information like display name, and app contact email, and click click create app button.

Now you click under setting basic and fill in all details of a domain name, terms, and services, privacy link, and choose a category.

Login with Facebook with SDK

Login with Facebook with SDK

Now on this page bottom click Add Platform and select Website click Next and now add the website URL in the site URL input field and click Save Changes.

Click settings under the Facebook link and this page enables Client OAuth login, Web OAuth login, login with the JavaScript SDK, log in from Devices, and add allow domain for the javascript SDK and click save changes button.

Step-2 Create migration and model

Now create social logins migration and model with the given command.


php artisan make:Model SocialLogin -m

Now update this on your database\migrations\create_social_logins_table.php file


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

class CreateSocialLoginsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('social_logins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('provider');
            $table->string('client_id')->unique();
			$table->string('user_id');
            $table->timestamps();
        });
    }

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

After that create user migration and model given below cmd.


php artisan make:model User -m

Now update database\migrations\create_social_logins_table.php table column.


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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Step-3 Create route

Now create route login route and social login route in routes/web.php file.


Route::post('/login/{provider}', [RegisterController::class, 'socialLogin']);

Step-4 Create controller and view file and Implement

Now create Registercontoller with the below command.


php artisan make:controller RegisterController

Update this code on app/http/controller/RegisterController.php


namespace App\Http\Controllers;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\SocialLogin;
use Illuminate\Support\Facades\Auth;
use Models\Customer;

class RegistrationController extends Controller
{
   public function socialLogin($provider, Request $request)
    {
            $fullName = $request->name;
            $clientId = $request->clientId;
            $email = $request->email;

			$socialLogin = SocialLogin::where('client_id', $clientId)->first();
			if(!empty(socialLogin)){
			$user = User::where('id', $socialLogin->user_id)->first();
			}else{
			$user = new User;
			$user->email 	= $email;
			$user->name 	= $fullName;
			$user->token 	= md5(uniqid(rand(), true));
			$user->save();

			$socialLogin = new SocialLogin;
            $socialLogin->client_id = $clientId;
            $socialLogin->user_id =  $user->id;
            $socialLogin->type =  $provider;
            $socialLogin->save();
			}
			if(!empty($user)){
			Auth::guard('web')->login($user);
			return response()->json([
                'url' => url('/dashboard'),
                'status' => 200
            ]);
			}else{
			return response()->json([
            'status' => 400
        ]);
			}
        }
    }

After that create a view file for login and add login with Facebook button and js code.


<div class="fb-login-button social-facebook custome-facebook-btn" scope="public_profile,email" onlogin="checkLoginState();" data-width="" data-size="large" data-button-type="continue_with" data-layout="default" data-auto-logout-link="false" data-use-continue-as="false"></div>

Now implement Login with Facebook with SDK.


function statusChangeCallback(response) {
        if (response.status === 'connected') {
            testAPI();
        }
    }

    function checkLoginState() {
        FB.getLoginStatus(function(response)
            statusChangeCallback(response);
        });
    }

    window.fbAsyncInit = function() {
        FB.init({
            appId: '{{ config('app.facebook_client_id') }}',
            cookie: true,
            xfbml: true,
            version: 'v12.0'
        });
    };

    function testAPI() {
        FB.api('/me', {
            locale: 'tr_TR',
            fields: 'name, email'
        }, function(response) {
				$.ajax({
                    type: "post",
                    url: "/login/facebook",
                    data: {
                        email: response.email,
                        name: response.name,
                        clientId: response.id,
                    },
                    headers: {
                        'X-CSRF-Token': csrfToken
                    },
                    success: function(data) {
                        if (data.status == 200) {
                            window.location.href = data.url;
                        }else{
						alert('Some thing went wrong, please try again');
						}
                    },
                });
        });
    }

Now your login with Facebook is implemented on your web. Facebook provided user details on the server, so when you test Facebook login then upload code on the server and then test.

Leave a Reply