Laravel Socialite Facebook Login

Create a Users table

We need to run database migrations to create user table but before doing that we need to modify it to store OAuth user.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password')->nullable(); // Set to nullable
        $table->string('token'); // OAuth Token
        $table->rememberToken();
        $table->timestamps();
    });
}

Create a Laravel Authentication

php artisan make:auth

Download the laravel socialite package

composer require laravel/socialite

Create Facebook App To Get Tokens

Go to the Facebook’s developers portal by following URL: https://developers.facebook.com/
Login via your Facebook account.

Create a new app then select facebook login product. After that, you can see the App id and App secret. You need to fill up some fields. Something like that

Configuration

Before using Socialite, you will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file

 'facebook' => [
        'client_id' => '3376905368878457',         // Your Facebook Client ID
        'client_secret' => 'f4c9f04c3344c7ef543222526e7874545', // Your Facebook Client Secret
        'redirect' => 'http://localhost:8000/login/facebook/callback',
    ],

Routing

Next, you are ready to authenticate users! You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. We will access Socialite using the Socialite facade:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
 
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Redirect the user to the facebook authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();

    }

    /**
     * Obtain the user information from facebook.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        $userSocial = Socialite::driver('facebook')->user();
        //return $userSocial->getId();
        //return $userSocial->getName();
        $findUser = User::where('email', $userSocial->email)->first();
        if ($findUser) {
            Auth::login($findUser);
            return "done with old";
        } else {
            $user           = new User;
            $user->name     = $userSocial->name;
            $user->email    = $userSocial->email;
            $user->password = bcrypt(123456);
            $user->save();
            Auth::login($user);
            return "done with new";
        }
    }
}

Of course, you will need to define routes to your controller methods:

Route::get('login/facebook', 'Auth\LoginController@redirectToProvider');
Route::get('login/facebook/callback', 'Auth\LoginController@handleProviderCallback');

Now we’ll be adding a link to our existing login form that will take the user to facebook authentication page. Edit your existing login view resources/views/auth/login.blade.php and add following HTML code.

<div class="panel-body">                         
    <div class="panel-heading">Login with Facebook</div>                            
    <div class="panel-body">
        <a class="btn btn-primary" href="{{'/login/facebook'}}">
            Facebook Login
        </a>
    </div>
</div>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s