Create Social Login In Laravel With Socialite

Published on : August 01,2022
Create Social Login In Laravel With Socialite

Hi dev,

In this article we will show you how to create social login using facebook,google and twitter in laravle. 

Social login is presently an fundamental portion of any location which performs client verification. It spares the clients a parcel of time, as they won’t ought to fill the entire shape. They fair sign up with their social account and following time they can log into the site by a single press.


The picture over appears a location that employments the social login for its sign up. In this instructional exercise, I will appear you how to include different social providers to a Laravel app utilizing Socialite a bundle built by Laravel for social authentication. Socialite right now supports verification with Facebook, Twitter, LinkedIn, Google, GitHub, and Bitbucket. For this instructional exercise, we are going include Facebook, Twitter, and Google Signups.

I’m using Laravel 8 for this article.



If you look inside database/migrations of your project, you will notice that Laravel already comes with some migrations for creating the users’ and password resets tables.

We will use the migration for creating the users’ table in this example but you can use any migration of your choice. There are a few things I want us to make changes to before creating the users’ table.

A user created via OAuth will have a provider and we also need a provider_idwhich should be unique. With Facebook, there are cases where the user does not have an email set up but a phone number and thus the hash sent back by the callback will not have an email resulting to an error. To counter this, you can set the email field to nullable but because the aim of this tutorial is to make it possible for a user to signup using any of Facebook, Twitter or Google with the same email and retain their profile, we will not make the email field nullable. Also, when creating users via OAuth we will not be passing any passwords, therefore, we need to set the password field in the migration nullable.

Here, we are doing the following: adding provider and provider_id columns to the users’ table. We also make the password field in the users’ table nullable.

The up method in your migration should look like this:

public function up()
    Schema::create('users', function (Blueprint $table) {

Next, on your terminal, run the migration with this command,

php artisan migrate

You need to add provider and provider_id to the list of fillable attributes in the model in our case User Model in app/User.php.

protected $fillable = [
    'name', 'email', 'image', 'provider', 'provider_id', 'password',


We will make use of the default Laravel authentication so that we can have a boilerplate for when the user login but we would make use of the social login for authentication and not the traditional register form. To make use of the default Laravel authentication, we need to run the command below:

php artisan make:auth

To start our local server, we need to run the command php artisan serve in our root directory, and visit the link given which in our case is We will notice the link for both Log in and Register has been added to the nav and users can now register and login using the traditional registration form which isn’t our focus for this tutorial.


Installation and Configuration of Socialite

Run the following command in the root directory of your Laravel project to add the package to your project’s dependencies:

composer require laravel/socialite

Once the installation is complete, we need to register its service provider in config/app.php.

In the providers array, of config/app.php add


In the aliases array of the same file, add

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

Now Socialite is all set up and you are ready to implement social login in your Laravel apps.

  • Visit the link to register your app.
  • Click on the button “Add a New App”, a modal would show which you’re required to fill in the details.



  • You’ll be redirected to a page as shown below


  • Click on Basic under the Settings tab by the left of the page.
  • You need to fill in the details of App Domains in our case localhost.


Scroll down and click on the button “Add Platform” it would show a modal and you’re to select website.



  • Add the following to config/services.php
'facebook' => [
    'client_id'     => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect'      => env('FACEBOOK_URL'),
],'twitter' => [
    'client_id'     => env('TWITTER_CLIENT_ID'),
    'client_secret' => env('TWITTER_CLIENT_SECRET'),
    'redirect'      => env('TWITTER_URL'),
],'google' => [
    'client_id'     => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect'      => env('GOOGLE_URL'),


  • Add the following to .env file


  • At this point, copy the content of APP ID and App Secret from the settings dashboard into FACEBOOK_CLIENT_ID and FACEBOOK_CLIENT_SECRET respectively.
  • We can need a controller at this point. Run the following command in your project root directory
php artisan make:controller <NamofController>
e.g php artisan make:controller SocialController


  • Add the following method to the controller created above
use Socialite;
class SocialController extends Controller
    public function redirect($provider)
     return Socialite::driver($provider)->redirect();

Note: The above method handles redirect from our site to the OAuth provider.


We need to call the route in routes/web.php

Route::get('login/{provider}', 'SocialController@redirect');

Note: The above route will be used for both Facebook and Google OAuth authentication to be integrated into this tutorial.


After successful login, it will redirect to the URL we have set as our callback URL, in our case http://localhost:8000/login/facebook/callback

The route that handles the callback is shown below:


The Callback method below will read the incoming request and retrieve the user’s information from the provider.

public function Callback($provider)
    $userSocial =   Socialite::driver($provider)->user();

When the callback is done, we will want to perform some functions which include: log in the user to their profile if the user exists or create a new user. To handle that, the callback method above becomes as shown below:

public function Callback($provider){
        $userSocial =   Socialite::driver($provider)->stateless()->user();
        $users       =   User::where(['email' => $userSocial->getEmail()])->first();if($users){
            return redirect('/');
        }else{$user = User::create([
                'name'          => $userSocial->getName(),
                'email'         => $userSocial->getEmail(),
                'image'         => $userSocial->getAvatar(),
                'provider_id'   => $userSocial->getId(),
                'provider'      => $provider,
            ]);         return redirect()->route('home');

Your controller is now as shown below

use Socialite;
use Auth;
use App\User;class SocialController extends Controller
    public function redirect($provider)
     "Line of Code"
    }    public function Callback($provider)
       "Lines of Code"


In both your registration and log in views, add this just below the closing tag of your form i.e. below the div containing the button.

resources/views/auth/register.blade.php and resources/views/auth/login.blade.php

    <div class="form-group row">
        <div class="col-md-6 offset-md-4">
             <a href="{{ url('/login/facebook') }}" class="btn btn-facebook"> Facebook</a>

Check the home.blade.php view and add the following:

<p>My name: {{Auth::user()->name}}</p>
<p>My Email: {{Auth::user()->email}}</p>
<img alt="{{Auth::user()->name}}" src="{{Auth::user()->image}}"/>

The Auth Facade would return the currently logged in user’s name, email and image respectively.

After successful login, you would see your name, email, and avatar on the homepage.

We Have Successfully Implemented Facebook login to our Laravel app using Socialite.


Twitter Login

  • Visit the link to register your app.

Note: Twitter doesn’t make use of localhost. For more information about that, you can check this link. Also, you’ll need to add your phone number to be able to create an app in twitter. Visit the link to add a phone number to your account if you don’t already.

  • After creating the app, click on “Settings” tab to set the Privacy Policy URL and Terms of Service URL. Without setting both URL, the callback method would return an error as it wouldn’t be able to return the user’s email address.
  • After updating the settings, click, on “Permissions” tab to give access to your app to be able to return the user’s email.
  • At the point, click “Keys and Access Tokens” tab at the top to get API Key and API Secret into TWITTER_CLIENT_ID & TWITTER_CLIENT_SECRET respectively of your .env file.

We need to create a callback method in the controller created earlier on for Twitter because the AbstractProvider for the TwitterProvider does not implement stateless(). i.e. stateless OAuth is not possible with the TwitterProvider in the Laravel Socialite package out of the box.

public function TwitterCallback()
    $twitterSocial  =   Socialite::driver('twitter')->user();
    $users          =   User::where(['email' => $twitterSocial->getEmail()])->first();if($users){
        return redirect('/home');
        $user = User::firstOrCreate([
            'name'          => $twitterSocial->getName(),
            'email'         => $twitterSocial->getEmail(),
            'image'         => $twitterSocial->getAvatar(),
            'provider_id'   => $twitterSocial->getId(),
            'provider'      => 'twitter',
        return redirect()->route('home');

The method above handles the callback for twitter only.


Call the method on your routes as shown below:

Route::get('login/twitter/callback', 'SocialController@TwitterCallback');

Now I would add a link to resources/views/auth/login.blade.php & resources/views/auth/register.blade.php.

<a href="{{ url('/login/twitter') }}" class="btn btn-twitter"> Twitter</a>

Note: The routes and controller have already been done earlier on.

At login using Twitter, the user is redirected to the page shown below if he is logged in to Twitter on the browser else to another page.


When we authorize the app, it would create the user if the email is not registered then it redirects to the home page with the details of the user or just redirects to the homepage for a register email address.

We Have Successfully Implemented Twitter login to our Laravel app using Socialite.


Google Login

  • Visit the link to register your app
  • Click on “select a project” in the left side of navigation which would show a modal where you’re expected to create a project from.


After the app is created, the redirects to the dashboard where we’re to Enable Apis and Services by following the link.


  • It redirects to the API library dashboard where you’re to select Google+ API under the Social section of the same page.
  • The social section looks as shown below
  • It redirects to a page where you enable the Google+ API to our Laravel app

You’ve successfully enabled Google+ API to your app, and it will redirect to another page but click on Credentials on the left side of navigation and select OAuth consent screen tab and fill out the details here.

Now we need to create credentials for your app. Click credentials in left side navigation and select Credentials. In the drop-down select OAuth client ID.

  • In the OAuth client ID screen, select the type of application, and fill the details,
  • Copy the content of client id and client secret to GOOGLE_CLIENT_ID & GOOGLE_CLIENT_SECRET respectively of your .env file.

Now we would add a link to resources/views/auth/login.blade.php & resources/views/auth/register.blade.php.

<a href="{{ url('/login/google') }}" class="btn btn-google-plus"> Google</a>

Note: The routes and controller have already been done earlier on.

If not logged in, we would be redirected to the page above.

When we authorize the app, it would create the user if the email is not registered then it redirects to the home page with the details of the user or just redirects to the home page for a registered email address.

We Have Successfully Implemented Google + login to our Laravel app using Socialite.



We have successfully implemented social login in Facebook, Twitter, and Google using Socialite — The official package provided by Laravel for OAuth authentication.


Hope it can help you…

Categories : Laravel

Tags : Laravel Packages Socialite

Praful Sangani
Praful Sangani
I'm a passionate full-stack developer with expertise in PHP, Laravel, Angular, React Js, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap. I enjoy sharing my knowledge by writing tutorials and providing tips to others in the industry. I prioritize consistency and hard work, and I always aim to improve my skills to keep up with the latest advancements. As the owner of Open Code Solution, I'm committed to providing high-quality services to help clients achieve their business goals.


order fenofibrate 160mg online fenofibrate 160mg drug buy fenofibrate 160mg without prescription

generic cialis india sildenafil for men buy viagra 50mg pills

pill zaditor 1 mg purchase tofranil sale buy tofranil 25mg pills

precose drug precose 50mg sale fulvicin 250 mg price

purchase aspirin pill purchase hydroquinone online cheap buy imiquad sale

cheap dipyridamole 25mg dipyridamole 100mg without prescription pravachol 20mg over the counter

order meloset 3mg online how to buy meloset danocrine cost

buy dydrogesterone pills for sale purchase empagliflozin generic order empagliflozin

pill florinef 100mcg cheap bisacodyl 5mg loperamide 2mg pills

buy prasugrel pills for sale generic prasugrel 10 mg cheap tolterodine 2mg

buy ferrous sulfate 100 mg without prescription ascorbic acid 500 mg canada generic betapace 40 mg

order pyridostigmine 60mg sale order mestinon 60 mg rizatriptan 5mg cheap

order enalapril 10mg without prescription purchase bicalutamide online cheap duphalac price

buy latanoprost eye drop for sale exelon ca buy rivastigmine 3mg generic

order premarin 600 mg dostinex 0.5mg tablet sildenafil 100mg canada

how to get omeprazole without a prescription singulair over the counter buy metoprolol no prescription

telmisartan without prescription brand molnunat 200 mg buy molnupiravir 200 mg generic

purchase cialis online sildenafil 100mg cheap guaranteed viagra overnight delivery usa

oral cenforce 100mg order aralen 250mg chloroquine generic

modafinil 200mg tablet order prednisone 10mg sale order deltasone online

buy cefdinir 300mg omnicef brand lansoprazole 15mg for sale

isotretinoin 10mg price generic accutane 10mg azithromycin without prescription

azipro 250mg oral azithromycin 500mg pills cheap neurontin without prescription

order generic atorvastatin 10mg proventil 100 mcg generic norvasc 10mg brand

spins real money slot online lasix 40mg over the counter

generic protonix 20mg buy generic protonix over the counter pyridium 200mg canada

casino game oral acticlate brand albuterol

Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles