Laravel 6 Facebook login tutorial

Laravel 6 login with the Facebook tutorial is today's topic. In this tutorial, I am going to demonstrate to you how to log in or sign up users with Facebook login API and save the user's detail into your Php MySQL database using Laravel 6. Also, we will learn how to switch to a registered test user Facebook. We will use Laravel official package socialite to integrate the Facebook login with your Laravel 6 application.

Let's get started

1. Install Fresh Laravel project

Install a Laravel 6 project by using the below command

composer create-project laravel/laravel social-login --prefer-dist

Before we start the application we need to configure the database in .env file. By default Laravel ships with .env.example. rename this file to .env. Now enter your database details. Below is the example of database configuration

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=socialLogin
DB_USERNAME=root
DB_PASSWORD=root

After the database configuration, we need to run the migration command. By default Laravel ships with user migration table. Enter the following command to run the migration

php artisan migrate

The above command will generate two tables users and password_reset in your MySQL database.

Once you are done with the installation navigate to you freshly installed Laravel project and type the following command.

php artisan serve

The above command will start the server at http://localhost:8000

2. Create Laravel authentication

Laravel auth

Laravel ships with basic authentication all you need to do is install the auth dependency by using the following command

composer require laravel/ui

The above command will pull all the auth dependency. Next, run the below command to generate authentication. I'll use bootstrap ui for the ready and go authentication

php artisan ui bootstrap --auth

The above command will generate the login and register scaffolding.You can now see newly added routes by navigating routes/web.php

 

3. Install Laravel socialite package for Facebook integration

To install the Laravel socialite we will use the composer to add the package dependencies. Enter the following command

composer require laravel/socialite

The above command will install the dependencies of the Laravel socialite package.

4. Get Facebook App Id

To implement Facebook social login, we need a Facebook developer app details like id and secret key. In this section, we will configure Facebook to get the app id and secret key.

Open a new tab in your browser and go to https://developers.facebook.com. Now enter the login details and click on get started option which you can find in the navigation bar. A popup box will appear as shown below.

facebook login first screen

Now Click on create the first app custom Facebook login button to get started.

Facebook social auth fill details

Now it will ask to enter the display name for your App. Enter a display name and your contact email. Now click on create App ID. you will now end up with the Facebook developer dashboard.

Facebook developer dashboard

Now click on Facebook login card to setup. It will ask you the login options to generate.

Facebook web click

You can choose as per your requirement. For this tutorial, we will be using the web option. Now click on the web and it will ask you to fill the basics information

Facebook basic information

For now, we will enter the Facebook app local development URL. Once the development part will be done. we will replace it with the production domain. There will be many steps click next and save the final step form

Facebook login details App id generate

 

Once we are done with the form. Now navigate to facebook login > setting which you can find in side navigation bar to set the redirect URI.

navigation to get app id and secret id

and click on save changes. now click on setting > basic to get the App ID and Secret key. 

Facebook setting page

 

Now we get the Facebook App ID and Secret Key. Update the services.php which you can find under config/services.php with the following code.

config/services.php

'facebook' => [
    'client_id' => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect' => 'http://localhost:8000/facebook/callback',
],

Now update the credentials in .env file with the following code

FACEBOOK_CLIENT_ID=485311532360000
FACEBOOK_CLIENT_SECRET=763d3e5a24502ad9f9e4e9439000000

Now we will set up the route. Copy and paste the following code

routes/web.php

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

Now that we have updated the routes in the web.php file. Now let's create a controller. Enter the following command to create a controller

5. Create a Controller

php artisan make:controller SocialAuthController

 we will put all the social login logic in the SocialAuthController controller. Copy and paste the following code

app/Http/Controllers/SocialAuthController.php

<?php

namespace App\Http\Controllers;

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

class SocialAuthController extends Controller
{
    public function redirect()
    {
        return Socialite::driver('facebook')->redirect();
    }

    public function callback(SocialAuthService $service)
    {
    	$user = $service->createOrGetUser(Socialite::driver('facebook')->user());
    	auth()->login($user);

        return redirect()->to('/home');
    }
}

6. Setting up the migration and model

Now we will create a table to store the Facebook provider id and user id. Enter the following command to create the migration and model

php artisan make:model SocialLogin -m

The above command will generate the migrations file and model. Now let's update the migration file. Copy and paste the following code

public function up()
{
    Schema::create('social_logins', function (Blueprint $table) {
        $table->integer('user_id');
        $table->string('provider_user_id');
        $table->string('provider');
        $table->timestamps();
    });
}

In the above code, we have added user_id, provider_user_id (Facebook provider user id) and the provider name. Now enter the following command to migrate 

php artisan migrate

The above command will create the social_logins table in the database. Now let's set up the relationship in the SocialLogin model file. Copy and paste the following code in app/SocialLogin.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

Now that we have set up the relationship between the user and social_login. Now we will create a service class that will be responsible for handling the user login.

7. Create a service class for user login handling

Now create a folder named with services inside app directory. Inside the services directory create a file named SocialAuthService.php. Now copy and paste the following code

app/Services/SocialAuthService.php

<?php

namespace App\Services;

use App\User;
use App\SocialLogin;
use Laravel\Socialite\Contracts\User as ProviderUser;

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

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

            $account = new SocialLogin([
                '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, 9999)),
                ]);
            }

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

            return $user;
        }
    }
}

The above code will check if Facebook provider user id is in the table it will return and login and if not it will create the user and set the login session. 

we are almost done. Now go to login.blade.php view file and update the login button with the following code.

<a href="{{url('/facebook/redirect')}}" class="btn btn-primary">Login with Facebook</a>

You can also set target="_blank" to open in a new tab or window

8. Test the Social Auth Login

To test the social auth login. Open your browser and enter the http://localhost:8000/facebook/redirect. Before you push the code in production make sure to remove development mode and put production URL else you will get an error 

This app is still in development mode facebook