Laravel 11 Socialite Login with Twitter / X Account Example

By Hardik Savani September 4, 2024 Category : Laravel

In this article, we will learn laravel 11 login with twitter account using socialite composer package. we can use with laravel ui, laravel jetstream and laravel breaze for login with twitter / X account.

As we know, social media becomes more and more popular in the world. Everyone has a social account like Twitter / X, Gmail, Facebook, etc. I think also most have Twitter accounts. So if your application has login with social, then it becomes awesome. You get more people to connect with your website because most of the people do not want to fill out the sign-up or sign-in form. If they login with social, then it becomes awesome.

In this example, we will install the Socialite composer package for login with Twitter Account. Then we will install Laravel UI for Bootstrap authentication. After that, we will add a login with Twitter button, allowing users to log in and register using their Gmail accounts. So, let's follow the steps below:

laravel 11 login with twitter

Step for Login with Twitter / X Account in Laravel 11?

  • Step 1: Install Laravel 11
  • Step 2: Install Laravel UI
  • Step 3: Install Socialite
  • Step 4: Create Twitter / X App
  • Step 5: Add twitter_id Column
  • Step 6: Create Routes
  • Step 7: Create Controller
  • Step 8: Update Blade File
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install Laravel UI

Now, in this step, we need to use Composer command to install Laravel UI, so let's run the below command and install the below library.

composer require laravel/ui

Now, we need to create authentication using the below command. You can create basic login, register, and email verification. We will run the below commands to create Bootstrap auth scaffold:

php artisan ui bootstrap --auth

Now, let's node js package:

npm install

let's run package:

npm run build

Step 3: Install Socialite

In the first step, we will install the Socialite Package, which provides an API to connect with Twitter accounts. So, first open your terminal and run the below command:

composer require laravel/socialite

Step 4: Create Twitter / X App

To create our Twitter app and receive the app credentials open the Twitter Developer Portal and sign up or log in.

To guide you through the steps listed above, I’ve included screenshots of the entire process below:

1. Create Project

2. On the dashboard page Click "Add App"

3. Fill in a App name

4. Copy the API Key and Secret and keep them for later use

5. Click "Set up" on the "App details" page

6. Fill in the form and make sure to:

- Check "Read"

- Check "Request email from users"

- As "Type of App" check "Web App, Automated App or Bot"

- Fill in "Callback URI / Redirect URI" with: http://localhost:8000/auth/twitter/callback

- Fill in "Website URL with: http://localhost:8000

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'),
    ],
]

Then you need to add twitter client id and client secret in .env file:

.env

TWITTER_CLIENT_ID=Ef3bb52lyXXXXD5NDnu1WHpgT
TWITTER_CLIENT_SECRET=QcYvZVeyk2gnHxx3HOjRzxpydFEiRyZLgCFXXXXXJLiwKRzpQH
TWITTER_CLIENT_REDIRECT=http://localhost:8000/auth/twitter/callback

Step 5: Add twitter_id Column

In this step, first, we have to create a migration to add the twitter_id in your user table. So let's run the below command:

php artisan make:migration add_twitter_id_column

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
    {
          
    }
};

Update mode like this way:

app/Models/User.php

<?php

namespace App\Models;

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',
        'twitter_id'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

Step 6: Create Routes

After adding the `twitter_id` column, first, we have to add new routes for Google login. So let's add the below route in the `routes.php` file.

routes/web.php


<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\TwitterController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
  
Route::controller(TwitterController::class)->group(function(){
    Route::get('auth/twitter', 'redirectToTwitter')->name('auth.twitter');
    Route::get('auth/twitter/callback', 'handleTwitterCallback');
});

Step 7: Create Controller

After adding the routes, we need to add a method for Twitter authentication. This method will handle the Twitter callback URL, etc. First, put the code below in your TwitterController.php file.

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('home');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'twitter_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('home');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Step 8: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php

@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="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email 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="row mb-3">
                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('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="row mb-3">
                            <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="row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-6 offset-md-4 mt-2">
                               <a class="btn btn-dark" href="{{ route('auth.twitter') }}"
                                style="display: block;">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-twitter-x" viewBox="0 0 16 16">
                                  <path d="M12.6.75h2.454l-5.36 6.142L16 15.25h-4.937l-3.867-5.07-4.425 5.07H.316l5.733-6.57L0 .75h5.063l3.495 4.633L12.601.75Zm-.86 13.028h1.36L4.323 2.145H2.865z"/>
                                </svg>
                                Login with Twitter
                            </a>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/login

Output:

I hope it can help you...

Shares