Laravel 10 Socialite Login with Twitter Account Example

 if your application has a login with social then it becomes awesome. you got more people to connect with your website because most of the people do not want to fill out the signup or sign-in form.

Step 1: Install Laravel App

composer create-project laravel/laravel example-SocialiteLogin

Step 2: Install JetStream

composer require laravel/jetstream

 you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. so run below command

php artisan jetstream:install livewire

Now, let's node js package:

npm install

Now,run package:

npm run dev

now, we need to run migration command to create database table:

php artisan migrate

Step 3: Install Socialite

composer require laravel/socialite

Step 4: Create Twitter App

First we need to create Twitter App and get ID and Secret. So, let's follow bellow steps as well:

Go to Twitter Developer App to click here: https://developer.twitter.com/en/portal/projects-and-apps

You can see bellow Steps:

1.  Login 

2. Create Project and Enter Project Name and Click on Next Button

3. Add Callback URL / Redirect URL  & Website URL

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 [
    ....
    'twitter' => [
        'client_id' => env('TWITTER_CLIENT_ID'),
        'client_secret' => env('TWITTER_CLIENT_SECRET'),
        'redirect' => env('TWITTER_CLIENT_REDIRECT'),
    ],
]

.env

TWITTER_CLIENT_ID=xyz
    TWITTER_CLIENT_SECRET=123
    TWITTER_CLIENT_REDIRECT=http://localhost:8000/auth/twitter/callback

Step 5: Add Database Column

run below command 

php artisan make:migration add_twitter_id_column

Migration

Migration

    <?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(): void
        {
            Schema::table('users', function ($table) {
                $table->string('twitter_id')->nullable();
            });
        }
      
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down(): void
        {
              
        }
    };

app/Models/User.php

<?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',
            'twitter_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

routes/web.php 

<?php
  
    use Illuminate\Support\Facades\Route;
      
    use App\Http\Controllers\TwitterController;
      
    /*
    |--------------------------------------------------------------------------
    | 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::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
        return view('dashboard');
    })->name('dashboard');
      
    Route::controller(TwitterController::class)->group(function(){
        Route::get('auth/twitter', 'redirectToTwitter')->name('auth.twitter');
        Route::get('auth/twitter/callback', 'handleTwitterCallback');
    });

Step 7: Create Controller

app/Http/Controllers/TwitterController.php 

<?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 TwitterController extends Controller
    {
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function redirectToTwitter()
        {
            return Socialite::driver('twitter')->redirect();
        }
              
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function handleTwitterCallback()
        {
            try {
            
                $user = Socialite::driver('twitter')->user();
             
                $finduser = User::where('twitter_id', $user->id)->first();
             
                if($finduser){
             
                    Auth::login($finduser);
            
                    return redirect()->intended('dashboard');
             
                }else{
                    $newUser = User::updateOrCreate(['email' => $user->email],[
                            'name' => $user->name,
                            'twitter_id'=> $user->id,
                            'password' => encrypt('123456dummy')
                        ]);
            
                    Auth::login($newUser);
            
                    return redirect()->intended('dashboard');
                }
            
            } catch (Exception $e) {
                dd($e->getMessage());
            }
        }
    }

Step 8: Update Blade File

resources/views/auth/login.blade.php 

<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>
            {{-- Laravel Login with Twitter Demo--}}
            <div class="flex items-center justify-end mt-4">
                <a class="btn" href="{{ route('auth.twitter') }}"
                    style="background: #1E9DEA; padding: 10px; width: 100%; text-align: center; display: block; border-radius:4px; color: #ffffff;">
                    Login with Twitter
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Run Laravel App:

php artisan serve

Now, Go to web browser, type the given URL and see the output:

http://localhost:8000/login