How to add Twitter Authentication to a Laravel Website

Laravel is a popular PHP framework used for developing web application. Laravel provides a many commands to help with on various development tasks. now I am explaining you how to add Twitter authentication functionality in Laravel website.

Table of Contents

1. Prerequisites

2. Install Laravel Socialite Package

3. add providers and aliases in your config file

4. Create a new Twitter app

5. Configure Twitter App Credentials in Laravel

6. Add Column in Users Migration Table

7. Create Controller For Login With Twitter

8. Add Routes

9. Login button for Twitter Login

1. Prerequisites

I assumes that you have already PHP and Composer installed on your computer. It have uses XAMPP’s Apache and MySQL installations or WAMP installed in you localhost system. if you have not already installed Laravel in your system then you can installed my Laravel 8 installation post. I have already setup Laravel 8 in my system called “laravel_webdeveloperindia.in”.

2. Install Laravel Socialite Package

if you have already Laravel 8 installed on your system then under this website folder you need to install Laravel Socialite package. run below command in laravel 8 setup.

composer require laravel/socialite

3. add providers and aliases in your config file

in your laravel folder go to config/app.php, add Socialite config to your providers and aliases arrays –

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

4. Create a new Twitter app

go to https://developer.twitter.com/en and create an account and register on twitter after register with Oauth v1 you will loggedin with this panel account .

here we need to generate twitter app key and app key secret key, it need to generate and stored it.

5. Configure Twitter App Credentials in Laravel

after created the client id and client secret, these keys required to set in the services array. So, just move to the config/services.php

 'twitter' => [
        'client_id' =>  env('TWITTER_CLIENT_ID'),
        'client_secret' => env('TWITTER_CLIENT_SECRET'),
        'redirect' =>   env('TWITTER_CLIENT_REDIERECT'),
    ],

you can provide directly twitter client id , twitter client secret and twitter client redirect here. or you can manage it .env file with use of above constant setting.

TWITTER_CLIENT_ID=”7o2ctAVMD5K…”
TWITTER_CLIENT_SECRET=”JfXWNn8A2cc…”
TWITTER_CLIENT_REDIERECT=”twitter-callback url”

6. Add Column in Users Migration Table

we need to add column, I will create a new migration file here. So, enter the below command.

php artisan make:migration add_twitter_id_column_in_users_table --table=users

after migration created, let’s put one column there and then it will migrate it.

<?php

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

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

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

after added code it need to run migrate command.

php artisan migrate

After the migration completed, then you will see the tables are migrated properly. Now, in the next step, we have to add this fillable data in the user model.

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\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'twitter_id'
    ];

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

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

7. Create Controller For Login With Twitter

php artisan make:controller SocialAuthController

after created controller , you need to add below code on SocialAuthController .

app\Http\Controllers\SocialAuthController.php

<?php

namespace App\Http\Controllers;

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

class SocialAuthController extends Controller
{
    /**
     * Redirect to twitter login
     *
     * @return void
     */
    public function twitterRedirect()
    {
        return Socialite::driver('twitter')->redirect();
    }

    /**
     * Twitter login authentication
     *
     * @return void
     */
    public function loginWithTwitter()
    {
        try {

            $twitterUser = Socialite::driver('twitter')->user();
            $user = User::where('twitter_id', $twitterUser ->id)->first();
            if($user){
                Auth::login($user);
                return redirect('/home');
            }

            else{
                $createUser = User::create([
                    'name' => $twitterUser ->name,
                    'email' => $twitterUser ->email,
                    'twitter_id' => $twitterUser ->id,
                    'password' => encrypt('test@123')
                ]);

                Auth::login($createUser);
                return redirect('/home');
            }

        } catch (Exception $exception) {
            dd($exception->getMessage());
        }
    }
}

8. Add Routes

add below route code in routes/web.php file.

web.php

Route::get('twitter', [App\Http\Controllers\SocialAuthController::class, 'twitterRedirect'])->name('auth/twitter');
Route::get('/auth/twitter-callback', [App\Http\Controllers\SocialAuthController::class, 'loginWithTwitter']);

9. Login button for Twitter Login

In the views/auth folder, open login.blade.php file and button code of twitter login.

         <a href="{{ route('auth/twitter') }}" class="btn btn-primary">
                                {{ __('Login with Twitter') }}

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>
                                <a href="{{ route('auth/twitter') }}" class="btn btn-primary">
                                    {{ __('Login with Twitter') }}
</a>

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

after added code you can able to check functionality have been applied.

Leave a Reply

Your email address will not be published. Required fields are marked *

5 + 4 =