How to Create Social Login with Twitter in Laravel 8 App

Laravel 8 Twitter social login tutorial; this detailed guide helps you learn how to create OAuth login with Twitter in laravel 8 application with the help of npm socialite package and Twitter authentication consumer API.

We want to give you an overview of this laravel 8 twitter login example; first, we set up the laravel project using the composer package. Next, we require to make the laravel and database connection, then move to install required dependencies, afterward create controller likewise the routes; lastly, we set up the login view and test login with Twitter functionalities.

Laravel 8 Twitter Social Login Integration Example

  • Step 1: Set Up Laravel Project
  • Step 2: Configure Database in Laravel
  • Step 3: Add Livewire Library
  • Step 4: Add Socialite Package
  • Step 5: Create Social Login Field in User Table
  • Step 6: Create Twitter App and Register Twitter Keys
  • Step 7: Create Controller
  • Step 8: Create Routes
  • Step 9: Add Login With Twitter Button in View
  • Step 10: Start Laravel Application

Set Up Laravel Project

Open terminal, execute the mentioned below command to create a new laravel project:

composer create-project laravel/laravel --prefer-dist laravel-demo-app

Configure Database in Laravel

Open and add database details in in .env file to configure the database in laravel app:

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

Add Livewire Library

In this step, you will add third-party packages Livewire and similarly Jetstream:

composer require laravel/jetstream

Next, add Jetstream library using the recommended command:

php artisan jetstream:install livewire

Next, execute set of commands to install NPM dependencies and run migration simultaneously:

npm install

npm run dev

php artisan migrate

Add Socialite Package

Type command to install socialite package in laravel:

composer require laravel/socialite

After installing the library, open config/app.php and register socialite classes as per given below example:

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

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

Create Social Login Field in User Table

Use following command to create a new migration file, using this file we will define new table properties in existing user table.

php artisan make:migration add_social_login_field

Open and add the suggested code in database/migration/add_social_login_field.php file:

<?php

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

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

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

Also, include social login table fields in app/Models/User.php file:

<?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',
        'social_auth_id',
        'social_auth_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',
    ];
}

Type command in terminal to evoke migration:

php artisan migrate

Create Twitter App and Register Twitter Keys

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

  • Create a new Twitter app in developers account.
  • Submit the API form.
  • From the API Keys tab get Twitter client id and secret key.

Open and add Twitter API keys and callback url in config/services.php file:

return [
    ...
    ...

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

Create Controller

In this step, you have to create a controller with the help of php artisan command:

php artisan make:controller TwitterLoginController

Open and update given below code in app/Http/Controllers/TwitterLoginController.php file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use Exception;
use Socialite;
use App\Models\User;


class TwitterLoginController extends Controller
{
    public function login()
    {
        return Socialite::driver('twitter')->redirect();
    }
       
    public function callbackTwitter()
    {
        try {
     
            $user = Socialite::driver('twitter')->user();
      
            $twitterUser = User::where('social_auth_id', $user->id)->first();
      
            if($twitterUser){
      
                Auth::login($twitterUser);
     
                return redirect('/dashboard');
      
            }else{
                $user = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'social_auth_id'=> $user->id,
                    'social_auth_type'=> 'twitter',
                    'password' => encrypt('user12345')
                ]);
     
                Auth::login($user);
      
                return redirect('/dashboard');
            }
     
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Create Routes

Create the routes using controller, include the following code in routes/web.php file:

<?php

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

 
Route::get('twitter-login', [TwitterLoginController::class, 'login']);
Route::get('callback/twitter', [TwitterLoginController::class, 'callbackTwitter']);

Add Login With Twitter Button in View

Open the views/auth/login.blade.php file, create a button with inline styling, pass the route name in the view file:

<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 Twitter Login Button --}}
            <div class="flex items-center justify-end mt-4">
                <a class="btn" href="{{ url('twitter-login') }}"
                    style="background: #069DE5; padding: 14px; text-align: center; display: block; border-radius:5px; color: #ffffff; width: 100%;">
                    Login with Twitter
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Start Laravel Application

Finally, test the app so execute command to run the laravel app:

php artisan serve

Here is the url on which your app runs:

http://127.0.0.1:8000/login

Laravel 8 Twitter social login tutorial