Laravel 5 Facebook authentication using Socialite Package

By Hardik Savani | April 15, 2016 | | 20136 Viewer | Category : Laravel Facebook API


Share this post:

In Nowdays, Social authentication is important to implement in website because nowdays most of the users or developer etc will connected with Social network like facebook, twitter, google+, gitbub etc. So, In this post i want to share with you how to do sign in with facebook and how to do sign up with facebook. Laravel 5 provide very easy way to implement login with your facebook account and register with your fb id. Laravel 5 provide us Socialite package that is help to social authentication. In this post we will make example same as like bellow preview and you can do that easily by using few following step:

Preview:

Step 1: Installation

In first step we will install Socialite Package that provide fb api to connect with facebook. So, first open your terminal and run bellow command:

composer require laravel/socialite

After install above package we should add providers and aliases in config file, Now open config/app.php file and add service provider and aliase.

'providers' => [

....

Laravel\Socialite\SocialiteServiceProvider::class,

],

'aliases' => [

....

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

],

Step 2: Create Facebook App

In this step we need facebook app id and secret that way we can get information of other user. so if you don't have facebook app account then you can create from here : https://developers.facebook.com/apps and after create account you can copy client id and secret from here :

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.php

return [

....

'facebook' => [

'client_id' => 'app id',

'client_secret' => 'add secret',

'redirect' => 'http://learnl52.hd/auth/facebook/callback',

],

]

Step 3: Create Facebook Login

In this step first we have to create migration for add facebook_id in your user table. so le's craete new migration and bellow column this way:

Migration

Schema::table('users', function ($table) {

$table->string('facebook_id');

});

After adding facebook_id column first we have to add new route for facebook login. so let's add bellow route in routes.php file.

app/Http/routes.php

Route::get('facebook', function () {

return view('facebookAuth');

});

Route::get('auth/facebook', 'Auth\AuthController@redirectToFacebook');

Route::get('auth/facebook/callback', 'Auth\AuthController@handleFacebookCallback');

After add route, we need to add method of facebook auth that method will handle facebook callback url and etc, first put bellow code on your AuthController.php file.

app/Http/Controllers/Auth/AuthController.php

namespace App\Http\Controllers\Auth;


use App\User;

use Validator;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\ThrottlesLogins;

use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

use Socialite;

use Auth;

use Exception;


class AuthController extends Controller

{


use AuthenticatesAndRegistersUsers, ThrottlesLogins;


protected $redirectTo = '/';


public function __construct()

{

$this->middleware('guest', ['except' => 'logout']);

}


protected function validator(array $data)

{

return Validator::make($data, [

'name' => 'required|max:255',

'email' => 'required|email|max:255|unique:users',

'password' => 'required|confirmed|min:6',

]);

}


protected function create(array $data)

{

return User::create([

'name' => $data['name'],

'email' => $data['email'],

'password' => bcrypt($data['password']),

]);

}


public function redirectToFacebook()

{

return Socialite::driver('facebook')->redirect();

}


public function handleFacebookCallback()

{

try {

$user = Socialite::driver('facebook')->user();

$create['name'] = $user->name;

$create['email'] = $user->email;

$create['facebook_id'] = $user->id;

$userModel = new User;

$createdUser = $userModel->addNew($create);

Auth::loginUsingId($createdUser->id);

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

} catch (Exception $e) {

return redirect('auth/facebook');

}

}

}

Now add addNew() in User model, that method will check if facebook id already exists then it will return object and if not exists then create new user and return user object. so open user model and put bellow code:

app/User.php

namespace App;


use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable

{


protected $fillable = [

'name', 'email', 'password','facebook_id'

];


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;

}

}

Ok, now at last we need to add blade view so first create new file facebookAuth.blade.php file and put bellow code:

resources/views/facebookAuth.blade.php

@extends('layouts.app')


@section('content')

<div class="container">

<div class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2" id="loginbox" style="margin-top:50px;">

<div class="panel panel-primary">

<div class="panel-heading">

<div class="panel-title">

Sign In

</div>

<div style="float:right; font-size: 80%; position: relative; top:-10px">

<a href="#">

Forgot password?

</a>

</div>

</div>

<div class="panel-body" style="padding-top:30px">

<div class="alert alert-danger col-sm-12" id="login-alert" style="display:none">

</div>

<form class="form-horizontal" id="loginform" role="form">

<div class="input-group" style="margin-bottom: 25px">

<span class="input-group-addon">

<i class="glyphicon glyphicon-user">

</i>

</span>

<input class="form-control" id="login-username" name="username" placeholder="username or email" type="text" value="">

</input>

</div>

<div class="input-group" style="margin-bottom: 25px">

<span class="input-group-addon">

<i class="glyphicon glyphicon-lock">

</i>

</span>

<input class="form-control" id="login-password" name="password" placeholder="password" type="password">

</input>

</div>

<div class="input-group">

<div class="checkbox">

<label>

<input id="login-remember" name="remember" type="checkbox" value="1">

Remember me

</input>

</label>

</div>

</div>

<div class="form-group" style="margin-top:10px">

<!-- Button -->

<div class="col-sm-12 controls">

<a class="btn btn-success" href="#" id="btn-login">

Login

</a>

<a class="btn btn-primary" href="{{ url('auth/facebook') }}" id="btn-fblogin">

<i class="fa fa-facebook"></i> Login with Facebook

</a>

</div>

</div>

<div class="form-group">

<div class="col-md-12 control">

<div style="border-top: 1px solid#888; padding-top:15px; font-size:85%">

Don't have an account!

<a href="#" onclick="$('#loginbox').hide(); $('#signupbox').show()">

Sign Up Here

</a>

</div>

</div>

</div>

</form>

</div>

</div>

</div>

</div>

@endsection

Ok, now you are ready to use open your browser and check here : URL + '/facebook'.



We are Recommending you: