Laravel 5.6 - Login with Facebook with Socialite
Hello Artisan,
In this tutorial, I would like to share with you how to login with facebook account on your laravel website. here I will use Socialite composer package for sign in with FB. so just follow bellow all step for authentication with Facebook in you laravel application.
In today's, Social authentication is important to implement on our website for increase traffic or making marketing, so you can connect with a Social network like facebook, twitter, google+, gitbub etc.
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.6 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:
Step 1: Install Socialite Package
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 alias.
config/app.php
'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.
Now you have to set app id, secret and call back url in config file so open config/services.php and .env file then set id and secret this way:
config/services.php
return [
....
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => env('FACEBOOK_CALLBACK_URL'),
],
]
.env
FACEBOOK_CLIENT_ID=xxxxxxxxx
FACEBOOK_CLIENT_SECRET=xxxxxxx
FACEBOOK_CALLBACK_URL=http://localhost:8000/auth/facebook/callback
Step 3: Create Migration and Model
In this step first we have to create migration for add facebook_id in your user table. so let's create new migration and bellow column this way:
Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddNewColunmUsersTable 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');
});
}
}
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
<?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;
}
}
Step 4: Create New Routes
In this step we need to create routes for facebook login, so you need to add following route on bellow file.
routes/web.php
Route::get('facebook', function () {
return view('facebook');
});
Route::get('auth/facebook', 'Auth\FacebookController@redirectToFacebook');
Route::get('auth/facebook/callback', 'Auth\FacebookController@handleFacebookCallback');
Step 5: Create New FacebookController
we need to add new controller and method of facebook auth that method will handle facebook callback url and etc, first put bellow code on your FacebookController.php file.
app/Http/Controllers/Auth/FacebookController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Socialite;
use Exception;
use Auth;
class FacebookController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function redirectToFacebook()
{
return Socialite::driver('facebook')->redirect();
}
/**
* Create a new controller instance.
*
* @return void
*/
public function handleFacebookCallback()
{
try {
$user = Socialite::driver('facebook')->user();
$create['name'] = $user->getName();
$create['email'] = $user->getEmail();
$create['facebook_id'] = $user->getId();
$userModel = new User;
$createdUser = $userModel->addNew($create);
Auth::loginUsingId($createdUser->id);
return redirect()->route('home');
} catch (Exception $e) {
return redirect('auth/facebook');
}
}
}
Step 6: Create Blade File
Ok, now at last we need to add blade view so first create new file facebook.blade.php file and put bellow code:
resources/views/facebook.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12 row-block">
<a href="{{ url('auth/facebook') }}" class="btn btn-lg btn-primary btn-block">
<strong>Login With Facebook</strong>
</a>
</div>
</div>
</div>
@endsection
Ok, now you are ready to use open your browser and check here : URL + '/facebook'.
I hope it can help you.....
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.