Hello Everyone, so in this article we will learn how to login with a Facebook account in Laravel application using the Socialite package.
Login with social media accounts is a simple process that improves the user experience, you got more people to connect with your website because most people do not want to fill out sign-up or sign-in forms. If there log in with social media like Facebook then it becomes awesome.
we are creating a simple feature to log in with a Facebook account in the Laravel application. Authentication user interface templates are required for this tutorial, and we are using Laravel Jetstream to streamline the Authentication UI process.
So if you want to also implement login with a Facebook account then I will help you with step-by-step instructions. let’s follow the tutorial and implement it.
Step 1: Install Laravel Application
Let’s create a fresh new Laravel project. It’s optional if you have already created then you may go ahead.
composer create - project laravel / laravel -- prefer - dist socialite - login - facebook - example
Step 2: Install JetStream
In this step, we will install Jetstream using the composer command. so let’s run this command.
composer require laravel / jetstream
Execute this command to generate authentication templates such as login, register, and email verification.
php artisan jetstream : install livewire
Now, let’s node js package.
Next, run the below command.
Step 3: Add Database Detail
Go to the .env file and configure your database details. Define the database name, user name, and password of your database.
DB_CONNECTION = mysql
DB_HOST = 127.0.0.1
DB_PORT = 3306
DB_DATABASE = database_name
DB_USERNAME = root
DB_PASSWORD =
now, we need to run the migration command to create a database table.
Step 3: Install Socialite
In this step install Socialite Package that provides API to connect with your Facebook account. So, run the below command.
composer require laravel / socialite
Step 4: Create Facebook App
Now you have to create Facebook App from here https://developers.facebook.com/ to get the App Id and Secret key. To create Facebook App You can also follow our tutorial https://bagisto.com/en/social-login-for-bagisto/
Then you have to set the App Id, Secret key, and call back URL in the config file, so open config/services.php and set the app id and secret this way:
return [
. . . .
'facebook' = > [
'client_id' = > env ( 'FACEBOOK_CLIENT_ID' ) ,
'client_secret' = > env ( 'FACEBOOK_CLIENT_SECRET' ) ,
'redirect' = > 'http://localhost:8000/auth/facebook/callback' ,
] ,
]
Then you have to add Facebook client id and client secret in the .env file:
FACEBOOK_CLIENT_ID = abc
FACEBOOK_CLIENT_SECRET = 12345
Step 5: Add Column In Database
In this step, You have to create a migration for adding facebook_id in your user table. So let’s run this command:
php artisan make : migration add_facebook_id_column_in_users_table -- table = users
Now go to the newly generated Migration file and add the facebook_id column value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
< ? php
use Illuminate \ Database \ Migrations \ Migration ;
use Illuminate \ Database \ Schema \ Blueprint ;
use Illuminate \ Support \ Facades \ Schema ;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up ( )
{
Schema :: table ( 'users' , function ( $ table ) {
$ table -> string ( 'facebook_id' ) -> nullable ( ) ;
} ) ;
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down ( )
{
}
}
Go to the model file app/Models/User.php and Update model this way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
< ? 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 ;
use Laravel \ Fortify \ TwoFactorAuthenticatable ;
use Laravel \ Jetstream \ HasProfilePhoto ;
use Laravel \ Sanctum \ HasApiTokens ;
class User extends Authenticatable
{
use HasApiTokens ;
use HasFactory ;
use HasProfilePhoto ;
use Notifiable ;
use TwoFactorAuthenticatable ;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $ fillable = [
'name' ,
'email' ,
'password' ,
'facebook_id'
] ;
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $ hidden = [
'password' ,
'remember_token' ,
'two_factor_recovery_codes' ,
'two_factor_secret' ,
] ;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $ casts = [
'email_verified_at' = > 'datetime' ,
] ;
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $ appends = [
'profile_photo_url' ,
] ;
}
Step 6: Create Routes
In this step, we have to add the route for Facebook login. so let’s add the route in the routes/web.php file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
< ? php
use Illuminate \ Support \ Facades \ Route ;
use App \ Http \ Controllers \ FacebookController ;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route :: get ( '/' , function ( ) {
return view ( 'welcome' ) ;
} ) ;
Route :: controller ( FacebookController :: class ) -> group ( function ( ) {
Route :: get ( 'auth/facebook' , 'redirectToFacebook' ) -> name ( 'auth.facebook' ) ;
Route :: get ( 'auth/facebook/callback' , 'handleFacebookCallback' ) ;
} ) ;
Step 7: Create a Controller
In This Step we need to create a new controller to add method of facebook auth that method will handle facebook callback url. So let’s run this command.
php artisan make : controller FacebookController
Now add code on your app/Http/Controllers/FacebookController.php file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
< ? php
namespace App \ Http \ Controllers ;
use Illuminate \ Http \ Request ;
use Laravel \ Socialite \ Facades \ Socialite ;
use Exception ;
use App \ Models \ User ;
use Illuminate \ Support \ Facades \ 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 ( ) ;
$ finduser = User :: where ( 'facebook_id' , $ user -> id ) -> first ( ) ;
if ( $ finduser ) {
Auth :: login ( $ finduser ) ;
return redirect ( ) -> intended ( 'dashboard' ) ;
} else {
$ newUser = User :: updateOrCreate ( [ 'email' = > $ user -> email ] , [
'name' = > $ user -> name ,
'facebook_id' = > $ user -> id ,
'password' = > encrypt ( '12345678' )
] ) ;
Auth :: login ( $ newUser ) ;
return redirect ( ) -> intended ( 'dashboard' ) ;
}
} catch ( Exception $ e ) {
dd ( $ e -> getMessage ( ) ) ;
}
}
}
Step 8: Update Blade File
Now we need to add a blade file view so first, create a new file resources/views/auth/login.blade.php file and add below code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
< x - guest - layout >
< x - jet - authentication - card >
< x - slot name = "logo" >
< x - jet - authentication - card - logo / >
< / x - slot >
< x - jet - validation - errors class = "mb-4" / >
@ if ( session ( 'status' ) )
< div class = "mb-4 font-medium text-sm text-green-600" >
{ { session ( 'status' ) } }
< / div >
@ endif
< form method = "POST" action = "{{ route('login') }}" >
@ csrf
< div >
< x - jet - label for = "email" value = "{{ __('Email') }}" / >
< x - jet - input id = "email" class = "block mt-1 w-full" type = "email" name = "email" : value = "old('email')" required autofocus / >
< / div >
< div class = "mt-4" >
< x - jet - label for = "password" value = "{{ __('Password') }}" / >
< x - jet - input id = "password" class = "block mt-1 w-full" type = "password" name = "password" required autocomplete = "current-password" / >
< / div >
< div class = "block mt-4" >
< label for = "remember_me" class = "flex items-center" >
< x - jet - checkbox id = "remember_me" name = "remember" / >
< span class = "ml-2 text-sm text-gray-600" > { { __ ( 'Remember me' ) } } < / span >
< / label >
< / div >
< div class = "flex items-center justify-end mt-4" >
@ if ( Route :: has ( 'password.request' ) )
< a class = "underline text-sm text-gray-600 hover:text-gray-900" href = "{{ route('password.request') }}" >
{ { __ ( 'Forgot your password?' ) } }
< / a >
@ endif
< x - jet - button class = "ml-4" >
{ { __ ( 'Log in' ) } }
< / x - jet - button >
< / div >
< div class = "flex items-center justify-end mt-4" >
< a class = "ml-1 btn btn-primary" href = "{{ url('auth/facebook') }}" style = "margin-top: 0px !important;background: blue;color: #ffffff;padding: 5px;border-radius:7px;" id = "btn-fblogin" >
< i class = "fa fa-facebook-square" aria - hidden = "true" > < / i > Login with Facebook
< / a >
< / div >
< / form >
< / x - jet - authentication - card >
< / x - guest - layout >
Use the following URL to see how far you’ve progressed:
http : //localhost:8000/login
Result :
I hope you will like the Tutorial and it will help you to learn Laravel Socialite Login with Facebook. Please comment below if you have any questions.
You can also hire laravel developers to build your custom solutions on laravel. For exploring the available extensions for Bagisto, you can check out the bagisto extension marketplace.