Laravel 10 Socialite OAuth Login with Twitter Example Tutorial

Last Updated on by in Laravel

Login with the social account is the most popular authentication process, allowing users to log in to any website without creating an account.

In this tutorial, we will explain how to login with Twitter in Laravel application using the laravel socialite package and Twitter consumer key and client keys (OAuth API).

For building Twitter social login integration in laravel, you will require twitter consumer keys, mainly client id and a secret that you can get from the Twitter developers’ account.

Apart from that, we will use the socialite social login package, which offers OAuth methods that reduce the pain of writing excessive code.

Laravel 10 OAuth Login with Twitter Example

  • Step 1: Install Laravel App
  • Step 2: Make Database Connection
  • Step 3: Install Laravel Livewire and Jetstream Packages
  • Step 4: Setting Up Socialite Library
  • Step 5: Update Social ID in Database
  • Step 6: Add Twitter Client ID and Secret
  • Step 7: Build Controller
  • Step 8: Add Routes
  • Step 9: Update Login View
  • Step 10: Run Development Server

Install Laravel App

In the beginning, open a terminal window and use the suggested command to create a fresh laravel application:

composer create-project laravel/laravel --prefer-dist laravel-twitter-login-example

Make Database Connection

Next, insert database details in .env config file, it makes the laravel connection with the database:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Install Laravel Livewire and Jetstream Packages

You have to use recommended command to install Jetstream into your new Laravel project:

composer require laravel/jetstream

Next, install Jetstream with Livewire:

php artisan jetstream:install livewire

After adding Jetstream, you need to install and build your NPM dependencies and migrate your database:

npm install

npm run dev

php artisan migrate

Setting Up Socialite Library

Next, you need to add socialite packge into laravel project with the help of following command:

composer require laravel/socialite

Open config/app.php file, plus add the following services in providers and aliases arrays:

....
....
'providers' => [
    ....
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
    ....
    ....
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
....
....

Update Social ID in Database

We have migrated the user table into the database, but it doesn’t have Twitter social login fields, hence we need to generate a new migration file to add the OAuth social login fields.

php artisan make:migration add_twitter_social_field

Get inside the database/migration/add_twitter_social_field.php file, add the given below properties migration file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddTwitterSocialField extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('twitter_id')->nullable();
            $table->string('oauth_type')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('twitter_id');
           $table->dropColumn('oauth_type');
        });
    }
}

Additionally, open app/Models/User.php file and register the social login properties in here as well.

<?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 array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'twitter_id',
        'oauth_type',
    ];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @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',
    ];
}

Further, execute command to run migration:

php artisan migrate

Add Twitter Client ID and Client Secret

Twitter consumer keys are required to login with Twitter in laravel, so getting a secret consumer key is a straightforward process:

  • Login Twitter developer account.
  • Create a Twitter app.
  • Submit the form.
  • Head over to the API Keys section; you can get your Consumer Key and Consumer secret keys from there.
  • Copy the consumer key (API key) and consumer secret from the screen into the laravel application.

Once, you have the Twitter consumer id and consumer secret, then move inside the config/services.php file and register the Twitter keys along with the callback url:

return [
    ...
    ...
    ...

   'twitter' => [
        'client_id' => 'xxxxxxxxxxxx',
        'client_secret' => 'xxxxxxxxxxxx',
        'redirect' => 'http://127.0.0.1:8000/auth/callback/twitter',
    ],
]

Build Controller

Now, generate a controller, this new controller will hold the Twitter OAuth programming logic.

php artisan make:controller TwitterController

Plus, open app/Http/Controllers/TwitterController.php file and place the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Auth;
use Exception;
use Socialite;
use App\Models\User;

class TwitterController extends Controller
{
    public function loginwithTwitter()
    {
        return Socialite::driver('twitter')->redirect();
    }
       

    public function cbTwitter()
    {
        try {
     
            $user = Socialite::driver('twitter')->user();
      
            $userWhere = User::where('twitter_id', $user->id)->first();
      
            if($userWhere){
      
                Auth::login($userWhere);
     
                return redirect('/home');
      
            }else{
                $gitUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'twitter_id'=> $user->id,
                    'oauth_type'=> 'twitter',
                    'password' => encrypt('admin595959')
                ]);
     
                Auth::login($gitUser);
      
                return redirect('/home');
            }
     
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Add Routes

Next, get into the routes/web.php file, here you need to define routes which will make the request via controller to handle the login with twitter in laravel:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TwitterController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
 
Route::get('auth/twitter', [TwitterController::class, 'loginwithTwitter']);
Route::get('auth/callback/twitter', [TwitterController::class, 'cbTwitter']);

Update Login View

We have added the livewire and jetstream into our laravel project, consequently it has created auth templates. Head over to views/auth/login.blade.php file, and create the login with Twitter button in the login tempalte to invoke the laravel auth app view.

<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 value="{{ __('Email') }}" />
                <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required
                    autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label value="{{ __('Password') }}" />
                <x-jet-input class="block mt-1 w-full" type="password" name="password" required
                    autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label class="flex items-center">
                    <input type="checkbox" class="form-checkbox" 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">
                    {{ __('Login') }}
                </x-jet-button>
            </div>


            {{-- Laravel Login with Twitter Demo--}}
            <div class="flex items-center justify-end mt-4">
                <a class="btn" href="{{ url('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 Development Server

Lastly, start the laravel development server using PHP artisan command:

php artisan serve

Test the application using the following url:

http://127.0.0.1:8000/login

Laravel Socialite Twitter Login

Conclusion

Ultimately, the laravel social login tutorial is completed.

In this comprehensive post, we figured out how to build and implement login with Twitter in laravel application using the laravel socialite package.