Laravel 10 Socialite Login with Twitter Example Tutorial

Using the Laravel 10 login with Twitter tutorial; this step-by-step guide explains how to integrate Laravel OAuth Login with Twitter Example with the help of a third-party composer socialite package from scratch.

To implement Twitter login functionality in Laravel, you can use the Socialite package provided by Laravel. Socialite is a simple and elegant way to authenticate with OAuth providers, including Twitter. Here’s a step-by-step guide to setting up Twitter login in a Laravel application.

Laravel OAuth Login with Twitter Example

Follow the following steps to implement Laravel Socialite login with Twitter:

  • Step 1: Install Laravel App
  • Step 2: Connect database to app
  • Step 3: Install and Setting Up Socialite Pacakage
  • Step 4: Add Twitter ID in Users Table
  • Step 5: Register Twitter Client ID and Secret
  • Step 6: Create Routes
  • Step 7: Construct Controller
  • Step 8: Update Login & Register View
  • Step 9: Start Laravel App

Install Laravel App

The first step begins with creating a new laravel application using the composer command.

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

Setup Database

After that, you need to add the database name, username equally important password in .env configuration file.

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

Install Socialite Package

Start by installing the Socialite package using Composer. Open your terminal and navigate to your Laravel project’s root directory, then run the following command.

composer require laravel/socialite

Get inside the config/app.php file then add socialite services in providers, as well as aliases arrays:

config/app.php

<?php

'providers' => [
    // Other service providers...

    Laravel\Socialite\SocialiteServiceProvider::class,
],

Aliese

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

Add Twitter ID in Users Table

In the next imperative task, we have to add the new value inside the users’ table, hence use the command to create a new migration file:

php artisan make:migration add_twitter_social_id_field

After that, head over to the database/migration/xxx_add_twitter_social_id_field.php file, update the suggested values in the newly generated 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();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('twitter_id');
        });
    }
}

Now, we have to register the newly created migration file’s value inside the User model file. Consequently, head over to the app/Models/User.php file and update the values.

<?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 HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'github_id',
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Now new table values have been added, just open the console and execute the command to run migration and update the database tables:

php artisan migrate

Register Twitter Client ID and Secret

Before you can use Twitter login, you need to create a Twitter application and obtain the API credentials (API key and secret). Visit the Twitter Developer portal (https://developer.twitter.com/) and create a new application. Once your application is created, retrieve the API key and secret.

  • 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.

Open the config/services.php file in your Laravel project. Add the following configuration to the services array:

'twitter' => [
     'client_id' => 'your client id',
     'client_secret' => 'your client secret',
     'redirect' => 'http://localhost:8000/callback/twitter',
 ],

Create Routes

Open the routes/web.php file and add the following route definition for Twitter login in laravel.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SocialController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
 
Route::get('auth/twitter', [SocialController::class, 'loginwithTwitter']);
Route::get('auth/callback/twitter', [SocialController::class, 'cbTwitter']);

Create Controller

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

php artisan make:controller SocialController

After creating controller go to app/controllers/SocialController.php and put the below code :

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Exception;
use Socialite;
use App\Models\User;
use Hash;

class SocialController 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{
                $twiterUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'twitter_id'=> $user->id,
                    'password' => Hash::make('12345678')
                ]);
     
                Auth::login($twiterUser);
      
                return redirect('/home');
            }
     
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Update Login & Register View

Add social Twitter buttons in login and register blade view. So open the Resources/Views/Auth/register.blade.php file and update the following code on it.

<div class="form-group row mb-0">
     <div class="col-md-8 offset-md-4">
        <a href="{{ url('/auth/twitter') }}" class="btn btn-primary"><i class="fa fa-twitter"></i> Twitter</a>
    </div>
</div>

Next, open the Resources/Views/Auth/login.blade.php file and update the below code on it.

<hr>
<div class="form-group row mb-0">
     <div class="col-md-8 offset-md-4">
        <a href="{{ url('/auth/twitter') }}" class="btn btn-primary"><i class="fa fa-twitter"></i> Twitter</a>
    </div>
</div>

Run Development Server

Now start the development server using the running the below command.

php artisan serve

Now you can check the register and login page have a twitter button enabled, Click the button you will be logged in using twitter in your Laravel app.

http://localhost:8000/login

That’s it! You have successfully implemented Laravel Social login with Twitter Account.

Leave a Comment