The Socialite login system for laravel framework

The first thing I will discuss is the meaning of Socialite:

Laravel Socialite: is a package developed to abstract away any social authentication complexities and boilerplate code into a fluent and expressive interface.

Socialite only supports Google, Facebook, Twitter, LinkedIn, Github, and Bitbucket as OAuth providers. What we need to do is install this library in our Laravel website, configure it, get API keys from a social site and we are good to go.

This Socialite is for Facebook Login system

These are the steps

Create a Laravel project Blog by typing the following things

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 two tables by default . 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.

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

click on the Developer. A Dashboard will display

Then add your First product. After that a another Dashboard will display with your App ID No…………

Click on the Settings go the Basic

There you will see your App Id and App Secret Id will show.

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.

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

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;
}
}
}

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 Author

User Profile: Ehochi Darlington

Hi Guys, I am a web developer, am working on Laravel Framework and a front-end developer. I love to share knowledge and idea.

Thanks to my Readers….

Email: darlingtonehochi@gmail.com

OR

confidenceiyke@gmail.com