Laravel5.4 - login with facebook in laravel

Hello today we are share with you one new articel/tutorials related how to login with facebook laravel. currently login with facebook laravel is mostly required in most of laravel application.

Some time you need to implement in your lravel application singup and singin functionality using facebook API. most of devloper very tired ith this problem, so we are make one very easy tutorial for login with facebook laravel and it share with you.

login with facebook laravel is a not big deal with laravel application. laravel's creater Taylor Otwell is created one laravel package called laravel socialite for laravel devloper to integrate login with facebook laravel in any laravel application to very easy way.

So, we are share with you how to use laravel socialite package in very easy way for integrate login with facebook in laravel application. simple follow this step and easily integrate login with facebook in your laravel application.

step : 1 Create new laravel project

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

step : 2 Install laravel/socialite package in your laravel application

composer require laravel/socialite

after intallation laravel/socialite package in your laravel application, then config it like tha..

step : 3 Open your config/app.php file and set provider class

'providers' => [
	........
	........
	Laravel\Socialite\SocialiteServiceProvider::class
],

step : 4 Open your config/app.php file and set this aliases

'aliases' => [
	........
	........
	'Socialite' => Laravel\Socialite\Facades\Socialite::class
],

step : 5 Create one facebook App

After configration laravel/socialite package above way then your need to craete one facebook app. how to create facebook app and how to get facebook app client_id and client_secret

Please first open this link Facebook Devloper Account, and here you can easyly creaete one app ang get your facebook app's client_id and client_secret

If you new for it so please watch this youtube video for "How to create facebook app right way"

step : 6 Open your config/services.php file and set your fb configration

No set your facebook client_id and client_secret like that


'facebook' => [
    'client_id' => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect' => env('CALLBACK_URL'),
 ],

step : 7 Open your .env file and set following values

FACEBOOK_CLIENT_ID=xxxxxxxxx
FACEBOOK_CLIENT_SECRET=xxxxxxx
CALLBACK_URL=http://localhost:8000/auth/facebook/callback

step : 7 Create laravel's auth

You all are you know laravel provide by defauls authentication but it not to show in your laravel fresh and new project, so first craete laravel auth using following command


php artisan make:auth

step : 8 Create new migration

If you don't have run migration then you not need to create new migration for it. simple open your uses table migration file which laravel bydefault provide

Simple open this file and put into some extra fields you want to like that...


<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('facebook_id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

step : 9 Create 2 following route in your routes/web.php file

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

step : 10 Open your views/auth/login.blade.php file

Now open your views/auth/login.blade.php file and add one extra button for login with facebook and set route for it like that.


@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" role="form" 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">
                                <button type="submit" class="btn btn-primary btn-block">
                                    Login
                                </button>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
                                    </label>
                                </div>

                                <a class="btn btn-link" href="{{ route('password.request') }}">
                                    Forgot Your Password?
                                </a>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <a href="{!! url('auth/facebook') !!}" class="btn btn-primary btn-block">
                                    Login with facebook
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

step : 11 Open your app/Http/Controllers/Auth/LoginController.php file

Now open your app/Http/Controllers/Auth/LoginController.php file and put following code.


<?php
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Socialite;
use Auth;
use Exception;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

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

    public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();
    }

    public function handleProviderCallback()
    {
        try {
            $user = Socialite::driver('facebook')->user();
        } catch (Exception $e) {
            return redirect('auth/facebook');
        }
        $authUser = $this->findOrCreateUser($user);

        Auth::login($authUser, true);

        return redirect()->route('home');
    }

    private function findOrCreateUser($facebookUser)
    {
        $authUser = User::where('facebook_id', $facebookUser->id)->first();

        if ($authUser){
            return $authUser;
        }

        return User::create([
            'name' => $facebookUser->name,
            'email' => $facebookUser->email,
            'facebook_id' => $facebookUser->id,
            'avatar' => $facebookUser->avatar
        ]);
    }
}

We are hope this tutorials is helpfull for you...

Also watch this video for any query "How to login with facebook in laravel"

 Prev post

Next post