Facebook Login

Hello developers, I would like to share step by step tutorial to create Facebook login using Laravel.

Tutorials for Facebook Login:

Create Facebook App

To get to Facebook API you have to create a Facebook App and specify the App ID and App Secret at the time of calling the Facebook API. Follow the step-by-step guide to create a Facebook App and generate App ID and Secret in the Facebook Developers Dashboard.

  1. Login to Facebook Developer account
  2. Click the My Apps link at the top navigation bar and select Add New App.
    • Enter the Display Name and Contact Email.
    • Click on the Create App ID button.
    • You will be redirected to the App Dashboard.
  3. Navigate to the Settings => Basic page.
    • Specify the App Domains and select the Category of your App.
    • Click Save Changes.
  4. Navigate to the Add a Product page by clicking the PRODUCTS(+) link at the left navigation menu panel.
    • Select Facebook Login to Set Up.
    • Select the Web as the App platform.
    • Enter the Site URL and Save.
  5. Navigate to the Facebook Login => Settings page.
    • In the Valid OAuth Redirect URIs field, enter the Redirect URL.
    • Click Save Changes.

Go to the Settings => Basic page, note the App ID and App Secret. This App ID and App secret allow you to access Facebook APIs.

Laravel

Make a project of  Laravel Facebook Login

Create a Laravel project by typing following command.

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

Go to that project and start the Laravel server by typing following command.

php artisan serve

Server starts at URL: http://localhost:8000

You need to configure your database in .env file.

Laravel ships with by default two tables. So run the following command in your terminal after setting up with the database.

php artisan migrate

Two tables of users and password_reset tables and one migration table generated in MySQL Database

Create a Laravel Authentication

Laravel gives us basic authentication. Laravel makes implementing authentication very simple. Truth be told, nearly everything is designed for you out of the box. We simply need to run one command in our terminal, and we are prepared to go.

php artisan make:auth

You can see in the terminal that “Authentication scaffolding generated successfully”

Now, if we switch to the routes => web.php file then there is one added route, and also our view is configured automatically.

<?php 

// web.php

Auth::routes();

now run

php artisan serve

Facebook login

Add Facebook App Id

Navigate to the config  =>  services.php file and put one another services array by the following code.

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

<?php

// services.php

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

Create controller for Facebook login

Now, we need to create one controller, which handles the Facebook Authentication routes.

php artisan make:controller FacebookLoginController

We need to implement two methods in this controller, which are following.

  • redirect():  Redirect our users to Facebook.
  • callback():  Handle callback from Facebook.
<?php

// FacebookLoginController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Socialite;

class FacebookLoginController 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 step is going to the routes => web.php file and register the routes.

<?php
 //web.php
 /*
 |--------------------------------------------------------------------------
 | Web Routes
 |--------------------------------------------------------------------------
 |
 | Here is where you can register web routes for your application. These
 | routes are loaded by the RouteServiceProvider within a group which
 | contains the "web" middleware group. Now create something great!
 |
 */
 Route::get('/', function () {
     return view('welcome');
 });
 Auth::routes();
 Route::get('/redirect', 'FacebookLoginController@redirect');
 Route::get('/callback', 'FacebookLoginController@callback');
 Route::get('/home', 'HomeController@index')->name('home');

Create View file

Now we just need to add the link to our route redirect which will further redirect the user to the Facebook. So go to the resources  => views  =>  auth  =>  login.blade.php and add one link like Login with Facebook.


<!-- login.blade.php -->
@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
                            </p>
</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="">
<p>                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </p>
</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>
<p>                                <a class="btn btn-link" href="{{ route('password.request') }}">
                                    Forgot Your Password?
                                </a>
                            </p>
</div>
</div>
<p style="margin-left:265px">OR</p>

<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

Create Migration and Model for Facebook Login

php artisan make:migration add_new_column_user_table –table=”users”

<?php


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


class AddNewColumnUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table("users", function (Blueprint $table) {
            $table->string('facebook_id');
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table("users", function (Blueprint $table) {
            $table->dropColumn('facebook_id');
        });
    }
}

Run artisan command to migrate

php artisan migrate

Modify user modal as possible

<?php


namespace App;


use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable
{
    use Notifiable;


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'facebook_id'
    ];


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public function addNew($input)
    {
        $check = static::where('facebook_id',$input['facebook_id'])->first();


        if(is_null($check)){
            return static::create($input);
        }


        return $check;
    }
}

Update controller

<?php
 // FacebookLoginController.php
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use Socialite;
 class FacebookLoginController 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()
 {
      
        <strong>try</strong> {
            $user = Socialite::driver('facebook')->user();
            $create['name'] = $user->getName();
            $create['email'] = $user->getEmail();
            $create['facebook_id'] = $user->getId();


            $userModel = <strong>new</strong> User;
            $createdUser = $userModel->addNew($create);
            Auth::loginUsingId($createdUser->id);


            <strong>return</strong> redirect()->route('home');


        } <strong>catch</strong> (Exception $e) {


            <strong>return</strong> redirect('redirect');


        }
 }
 }