When you are creating an authentication for the user login then you always take care of secure login. Generally, you create an email or username and a password for the login. Sometimes, you need to store the login session in the browser storage to maintain the login state of the user. But, what if you want to create a Facebook login in any application? If you create custom functionality to login with Facebook in Laravel then it would be a difficult task. But, what if you go with a package in Laravel. Yes, you can use the Laravel Socialite package to create the social login for your application. By using this package, you can create a Facebook login, Google Login, LinkedIn, Github, Twitter, etc. So, today, in this post, I will guide you on creating the socialite login in Laravel 8 using Facebook.
So, let’s start by creating a new project in Laravel 8.
Prerequisites
Before moving to this post, please make sure you are ready with the following configuration.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create Project For Facebook Login in Laravel 8
To create this project, I will be using composer here. So, just open the terminal or command prompt and hit the below command.
composer create-project --prefer-dist laravel/laravel laravel-facebook
It will install the new setup of Laravel 8 inside a folder named laravel-facebook.
How to Schedule Tasks with Cron Job in Laravel 8
Create and Configure Database
For the database management, I am using MySQL command line.
CREATE DATABASE laravel_facebook;
After creating the database, let’s connect it with the Laravel 8 application.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_facebook
DB_USERNAME=root
DB_PASSWORD=root
After connecting the database, we will move to the next step.
Install UI Authentication in Laravel 8
For managing the login and session for the logged user, we will have to create a login system. But, why we will create it manually. We will be installing the UI Auth package.
composer require laravel/ui
This package installation will take a couple of minutes. After completing the installation, we will install the auth scaffolding.
Import and Export CSV and Excel File in Laravel 8
Install Auth Scaffolding
Here, we will install auth scaffolding for this UI Auth package. So, here, we will use vue auth. You can use bootstrap auth also.
php artisan ui vue --auth
After running the auth scaffolding, it will ask to install npm.
npm install && npm run dev
After installing the npm, it will build the CSS and JS file as showing below.
After the build of the UI auth, you will be able to see the Login and Register options in the homepage.
You can see here, we have the options for Login and Register. Now, we will implement the Facebook login in Laravel 8. So, first of all, we will have to install the package for the socialite login.
How to Generate PDF File in Laravel 8 Using DOM PDF
Install Laravel Socialite Package
For managing social login there is a package called socialite. This package is very helpful for managing social login in Laravel application. Hence, we will be installing this package using below command.
composer require laravel/socialite
This package will take a couple of minutes to install the socialite package.
Create REST API in Laravel 8 Using JWT Authentication
Add Provider and Alias for Socialite Package
After installing the package, we will have to add the provider and alias for this one. So, for adding the provider, you will have to go inside the config/app.php file. You will see the providers array. So, put the below service provider there. After the providers section, you will find the aliases array. Next, you will have to create one alias for this as showing below.
'providers' => [
...
...
...
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
...
...
...
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
In the next step, we will create a facebook app for authenitcating facebook login.
RESTful APIs For Todo App Using Passport Auth in Laravel 8
Create and Configure App in Facebook
In the very first step of Facebook Login in Laravel 8, we will have to create an app in facebook developer accounts. Take a look at the below image, you can see an option of My Apps in the right corner.
Now, go to My Apps section, and create a new app there.
Then choose the app type. Here, we are going to create Facebook Login, so, you have to opt Consumer in the app type.
In the next step, you have to put the App name, contact details. So, just fill out the details and proceed to Create App.
After creating the app, you will have the App. Go to the Settings->basic and copy the App ID and secret.
In the next step, we will configure the App Id and client secret in the Laravel application.
How to Implement Invisible reCAPTCHA in Laravel 8
Add Facebook Login Service in Laravel 8
In the project, open the config/services.php file and put the array as showing below. Here, we are creating Facebook login functionality, so we will define the facebook array and inside the facebook array, we will put client id, secret and the callback URL.
return [
...
...
...
'facebook' => [
'client_id' => 'FACEBOOK_APP_CLIENT_ID',
'client_secret' => 'FACEBOOK_APP_CLIENT_SECRET',
'redirect' => 'CALLBACK_RETURN_URL',
],
After putting the service, we will create a column in users_migration table. In the redirect, you have to set the callback return URL on which the response will be coming after the login.
Create Column in Users Migration Table
Here, to manage the login authentication using Facebook, we will store the facebook user id in the users table. In order to do that, we will add a column in the users table.
php artisan make:migration add_fb_id_column_in_users_table --table=users
The above command will create a new migration for the users table.
Now, after creating the migration file, just add a column as showing below.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddFbIdColumnInUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('fb_id')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('fb_id');
});
}
}
Once, you have added the column, just migrate the tables.
php artisan migrate
After the successful migration, you will be able to see a new column in the users table.
Create Authentication in Laravel 8 Using Laravel Breeze
Add Fillable Data in Users Model
After the migration, you will have to set the fillable data in the Users model. Here, I have added the fillable fields.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'fb_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Create Controller
For managing the Facebook login authentication, we will create a controller.
php artisan make:controller SocialAuthController
After creating the above controller, just put the below snippet there.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Validator;
use Socialite;
use Exception;
use Auth;
class SocialAuthController extends Controller
{
/**
* Redirect to facebook login
*
* @return void
*/
public function facebookRedirect()
{
return Socialite::driver('facebook')->redirect();
}
/**
* Facebook login authentication
*
* @return void
*/
public function loginWithFacebook()
{
try {
$facebookUser = Socialite::driver('facebook')->user();
$user = User::where('fb_id', $facebookUser->id)->first();
if($user){
Auth::login($user);
return redirect('/home');
}
else{
$createUser = User::create([
'name' => $facebookUser->name,
'email' => $facebookUser->email,
'fb_id' => $facebookUser->id,
'password' => encrypt('test@123')
]);
Auth::login($createUser);
return redirect('/home');
}
} catch (Exception $exception) {
dd($exception->getMessage());
}
}
}
In the next step, we will have to add some routes for the above functions.
User Authentication in Laravel 8 Using UI Auth Package
Add Routes for Laravel Facebook Login
For the controller functions, add the below routes in the web.php file.
Route::get('facebook', [SocialAuthController::class, 'facebookRedirect'])->name('auth/facebook');
Route::get('facebook/callback', [SocialAuthController::class, 'loginWithFacebook']);
After adding the routes, we will have to create a Facebook login button in the auth login page.
Create Facebook Login Button in Auth Login
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
@csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-secondary">
{{ __('Login') }}
</button>
<!-- Facebook Login Button -->
<a href="{{ route('auth/facebook') }}" class="btn btn-primary">
{{ __('Login with Facebook') }}
</a>
</div>
<div class="col-md-8 offset-md-4">
@if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
@endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Now, we are done for the facebook login. We can check the result by running the application.
Remove Uploaded Image in Laravel 8 From Public Folder
Check the Facebook Login Result
Run the application and check the result. When you will click on the Login option available by the Auth scaffolding. On the login page, we already added a button for Facebook login.
When you will click on the Login with Facebook button, it will redirect you to the official login page with some parameters in the URL. Here, currently, I haven’t logged in to the Facebook account. Hence, it is asking for the login.
Once, you enter your login credentilas and click on Login button, it will ask for the permission to allow. Just allow all the permission to authenticate and access the profile detail.
Conclusion
So, finally, we completed the Laravel socialite login with the Facebook tutorial. The socialite package is easy to install and configure in Laravel. Similarly, we will create the Google Login, Github Login, Twitter, and LinkedIn in the upcoming posts. So, keep practicing the code, and don’t forget to share if find it helpful. Also, for any kind of issue or doubt, please don’t hesitate to put your comments below.
Leave a Reply