Implementing social account authentication is very popular these days. It is easy and powerful method for user authentication, social account authentication takes less effort from user for registration or login on your system. there is no need for the user to remember the username and password.
Table Of Content
1 Prerequisites
1.) PHP version of 8.2
2.) MySql
3.) Twitter Account
2 Introduction
In this article, I am going to show you how to implementation social account authentication to your Laravel application.
We’ll be using Laravel external libraries such as Socialite and Breeze Package.
Laravel provides a package to authenticate with OAuth providers using Laravel Socialite. Although, this package is not pre-installed in laravel.
Laravel Socialite supports authentication only for the following social account providers:
Facebook
Twitter
LinkedIn
Google
GitHub
GitLab
Bitbucket
Slack.
3 Create / Install a Laravel Project
3.1 Install Laravel Project
First, make sure your computer has a composer.
Use the following command to install new Laravel Project.
Upon logging in, the user's record will be stored in the database. This process involves accessing the .env file to input and define the database credentials.
We will use Laravel Breeze as an example of our existing authentication implementation.
4.1 Install Breeze Package
Use the following command to Install Laravel Breeze Package
composer require laravel/breeze --dev
After Composer has installed the Laravel Breeze package, you should run the breeze:install Artisan command. This command publishes the authentication views, routes, controllers, and other resources to your application.
php artisan breeze:install
php artisan migrate
npm install
npm run dev
4.2 Install Socialite Package
Use the following command to Install Laravel Socialite Package
composer require laravel/socialite
5 Create a Twitter Developer Application
5.1 Login into Twitter Developer Account
If you have Twitter Developer Account Go to https://developer.twitter.com/, else you can easily create one directly from the Twitter Developers Portal.
5.2 Create an Application
"Add App" in the Twitter Developer Portal
Update App Info in the Twitter Developer Portal
After Creating application , you will receive a API Key and API Key Secrets. copy these keys into your .env file.
5.3 Setup User Authentication Settings
In Following Screen Click "Set up" Button to update settings
In Following Screen select "Read" Option and Enable Request email from users" Option
In "Type Of App" select "Web App, Automated App or Bot" Option
It will redirected to the following screen and fill the detail about our app and fill the redirect URL. This is the URI that we will use to redirect user after they choose their Twitter account to login to our web. For example here I use http://127.0.0.1:8000/callback/twitter for the callback URI.
In Following Screen add a Privacy policy and Terms of Services URL
6 Configure Twitter App Credentials
6.1 Add the Twitter API Credentials in .env
Insert the Client ID and Client Secret key and redirect URI into the .env file, Which we obtained from previous step TWITTER_CLIENT_ID and TWITTER_CLIENT_SECRET. Additionally, include a new key in the .env file called TWITTER_REDIRECT_URI and populate it with the callback URI used in the Twitter API Console.
TWITTER_CLIENT_ID=Your Client ID
TWITTER_CLIENT_SECRET=Your Client Secret
TWITTER_REDIRECT_URI=http://127.0.0.1:8000/callback/twitter
6.2 Add the Twitter API .env key in config/services.php
Open the config/services.php file and Insert the Twitter OAuth Credentials
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('twitter_id')->after('password')->nullable()->unique();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('twitter_id');
});
}
};
Use the following command to run the migration to update your database.
php artisan migrate
6.4 Update the User Model
In your User model , Include twitter_id in the fillable array of 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;
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',
];
}
}
?>
7 Create New Controller - TwitterLoginController
Now create a controller "TwitterSocialiteController" and add redirectToTwitter() and handleTwitterCallback() methods
Use the following artisan command to Create Controller.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Auth;
use Exception;
use Socialite;
class TwitterSocialiteController extends Controller
{
public function redirectToTwitter()
{
// redirect user to "login with Twitter account" page
return Socialite::driver('twitter')----->redirect();
}
public function handleCallback()
{
try {
// get user data from Twitter
$user = Socialite::driver('twitter')->user();
// find user in the database where the social id is the same with the id provided by Twitter
$finduser = User::where('twitter_id', $user->id)->first();
if ($finduser) // if user found then do this
{
// Log the user in
Auth::login($finduser);
// redirect user to dashboard page
return redirect('/dashboard');
}
else
{
// if user not found then this is the first time he/she try to login with Twitter account
// create user data with their Twitter account data
$newUser = User::create([
'name' => $user->name,
'email' => $user->email,
'twitter_id' => $user->id,
'password' => bcrypt('my-twitter'), // fill password by whatever pattern you choose
]);
Auth::login($newUser);
return redirect('/dashboard');
}
}
catch (Exception $e)
{
dd($e->getMessage());
}
}
}
?>
8 Define a Route for Socialite Login with Twitter
Define routes for the TwitterSocialiteController in the web.php file routes/web.php
Route::get('auth/twitter', [TwitterSocialiteController::class, 'redirectToTwitter']); // redirect to Twitter login
Route::get('callback/twitter', [TwitterSocialiteController::class, 'handleCallback']); // callback route after Twitter account chosen
9 Update Login Blade File With Twitter Button
Create the Link in the login view to Show Twitter Sign-in Button resources/views/auth/login.blade.php
Use the following artisan command to Test the App.
php artisan serve
Visit the URL http://127.0.0.1:8000
12 Conclusion
That’s all we need to do.
Now the Twitter Sign-In Implementation completed in Laravel application with the help of Laravel Socialite and Breeze package.