Facebook Login with Laravel and Socialite

Facebook Login with Laravel and Socialite

 

Facebook Login with Laravel 8 and Socialite




step 1: Install Laravel Project

First Install a Laravel project to run the below command

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

step 2: composer self-update --2 

First, fix a Laravel project to run the below command

composer self-update --2

step 1: Install Laravel/socialite

Socialite is a Laravel package that handles 0Auth logins. Socialite supports authentication with Facebook, Twitter, Linked In, Google, GitHub, GitLab, and Bitbucket. There are other socialite adapters for other platforms. Let's install it:

composer require laravel/socialite

Step 2: Setup Database Credentials

Create a new database custom auth and now open your .env file and add your database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=#Your database name
DB_USERNAME=root #Your database username
DB_PASSWORD=#Your database password
 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('role_id')->nullable();
            $table->string('role_name')->nullable();
            $table->string('provider_id')->unique()->nullable();
            $table->string('avatar')->nullable();
            $table->string('email')->unique();
            $table->string('password')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

We have set password column to nullable so both Laravel and Facebook log-in can be stored in the same table. We have added a nullable provider_id column which is the id of the Facebook user and an avatar which is the image of that user.

Before running migrations, add this line in the boot() method of your AppServiceProvider.php located in app\Providers directory:

Now run the migration command and generate a table in the database.
\Schema::defaultStringLength(191);

The above line will set the default length of a string column to 191. Now we can create tables by running the migrate command:

Now run the migration command and generate a table in the database.
php artisan migrate

step 3: route

//============================== Login Socialite ===========================//
Route::get('/','App\Http\Controllers\Socialite\LoginController@redirectToProvider')->name('login.facebook');
Route::get('/callback','App\Http\Controllers\Socialite\LoginController@handleProviderCallback');

step 4: Controller

Let's create the LoginController:
php artisan make:controller Socialite/LoginController

<?php
namespace App\Http\Controllers\Socialite;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use Socialite;
use App\Models\User;
class LoginController extends Controller
{
    // login facebook
    public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();
    }
    public function handleProviderCallback()
    {
        try{
            //if Authentication is successfull.
            $user = Socialite::driver('facebook')->user();
            /**
             *  Below are fields that are provided by
             *  every provider.
             */
            $provider_id = $user->getId();
            $name = $user->getName();
            $email = $user->getEmail();
            $avatar = $user->getAvatar();
            //$user->getNickname(); is also available
            // return the user if exists or just create one.
            $user = User::firstOrCreate([
                'provider_id' => $provider_id,
                'name'        => $name,
                'email'       => $email,
                'avatar'      => $avatar,
            ]);
            /**
             * Authenticate the user with session.
             * First param is the Authenticatable User object
             * and the second param is boolean for remembering the
             * user.
             */ 
            Auth::login($user,true);
            //Success
            return redirect()->route('home');
        }catch(\Exception $e){
            //Authentication failed
            return redirect()->back()->with('status','authentication failed, please try again!');
        }
    }
}

Step 5: resources/view/auth/login

@extends('layouts.app')
@section('content')
    <div class="login-form">
        <form method="POST" action="{{ route('login') }}">
            @csrf
            <div class="text-center">
                <a href="" aria-label="Space">
                    <img class="mb-3 logo-image" src="{{URL::to('assets/images/logo_log.png')}}" alt="Logo" width="60" height="60">
                </a>
            </div>
            <div class="text-center mb-4">
                <h1 class="h3 mb-0">Please sign in</h1>
                <p>Signin to manage your account.</p>
            </div>
            @if(session()->has('error'))
                <div class="alert alert-danger">
                    {{ session()->get('error') }}
                </div>
            @endif
            <div class="js-form-message mb-3">
                <div class="js-focus-state input-group form">
                <div class="input-group-prepend form__prepend">
                    <span class="input-group-text form__text">
                    <i class="fa fa-envelope form__text-inner"></i>
                    </span>
                </div>
                <input type="email" class="form-control form__input @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}"  placeholder="Email" autocomplete="email">
                @error('email')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
                </div>
            </div>
        <div class="form-group">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            <i class="fa fa-lock"></i>
                        </span>
                    </div>
                    <input type="password" class="form-control @error('password') is-invalid @enderror" name="password"  placeholder="Password" autocomplete="new-password">
                    @error('password')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                    @enderror
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-6">
                  <!-- Checkbox -->
                  <div class="custom-control custom-checkbox d-flex align-items-center text-muted">
                    <input class="custom-control-input"type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
                    <label class="custom-control-label" for="remember">
                      Remember Me
                    </label>
                  </div>
                  <!-- End Checkbox -->
                </div>
                <div class="col-6 text-right">
                  <a class="float-right" href="{{route('forget-password')}}">Forgot Password?</a>
                </div>
            </div>
            <div class="form-group mb-3">
                <button type="submit" class="btn btn-primary login-btn btn-block">Signup</button>
            </div>
            <div class="text-center mb-3">
                <p class="text-muted">Have an account? <a href="{{route('register')}}">Signin</a></p>
            </div>
            <div class="or-seperator"><i>OR</i></div>
            <div class="row mx-gutters-2 mb-4">
                <div class="col-sm-6">
                    <button id="oauth-login-google_oauth2" class="btn btn-outline-secondary" type="submit">
                        <img alt="Google" title="Sign in with Google" class="google" src="{{URL::to('assets/images/google.png')}}" loading="lazy">
                        <span>Sign in with Google</span>
                    </button>
                </div>
                <div class="col-sm-6">
                    <a href="{{route('login.facebook')}}">
                        <button id="oauth-login-google_oauth2" class="btn btn-outline-secondary" type="button">
                            <img alt="Google" title="Sign in with Google" class="google" src="{{URL::to('assets/images/twitter.png')}}" loading="lazy">
                            <span>Sign in with Twitter</span>
                        </button>
                    </a>
                </div>
            </div>
            <p class="small text-center text-muted mb-0">All rights reserved. © Space. 2020 soengsouy.com.</p>
        </form>
    </div>
@endsection

Step 6: Facebook Auth0 Login Credentials

Let's get the credentials for our Facebook login from the Facebook developer's site.

Go to the developer's site and log into your Facebook account and hover over to the My Apps link on the right side, it will open a dropdown listing all your apps. Click on Add New App:





Step 7: config/services.php

Open the services.php from config directory and add Facebook config details at the end of the array:

'facebook' => [
    'client_id' => env('FACEBOOK_KEY'),
    'client_secret' => env('FACEBOOK_SECRET'),
    'redirect' => env('FACEBOOK_REDIRECT_URI')
],

Step 8: .env

FACEBOOK_KEY=your_fb_id
FACEBOOK_SECRET=your_fb_secret_key
FACEBOOK_REDIRECT_URI=http://localhost:8000/callback

Reactions

Post a Comment

0 Comments

close