When you want to create the login with Twitter in Laravel 8, you will require the socialite package. This package will allow interacting with the social account login using OAuth. In this entire authorization of Twitter login, the security things are managed by the OAuth system. It makes a secure authentication between the project and the user account. So, it is very much safe for user authorization for your application. The Twitter Login in Laravel 8 will require a developer account. But, if you don’t have then don’t worry. In this post, I will show you the complete steps of creating the functionality of Login with Twitter in the Laravel web project. I have already created the socialite Facebook Login, Google Login, and LinkedIn Login.
Prerequisites
I assume you are ready for creating the Laravel 8 project. If not then you will require to have the below configurations.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create New Project in Laravel 8
Here, I am going to create a new project in Laravel using the composer. So, in the terminal, I have hit the below command.
composer create-project --prefer-dist laravel/laravel laravel-socialite
After creating the project, you will require the database configuration for this project.
Create and Configure Database
For managing the user account, you will require a database connected with the application. Hence, create a new database. Here, I am using the MySQL database management system.
CREATE DATABASE laravel_socialite;
Once, you created the database, let’s connect it with our Laravel 8 project for the Twitter Login.
Hence, to configure the database credentials, just find the .env file. Now, in the DB section, just put the database detail as showing below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_socialite
DB_USERNAME=root
DB_PASSWORD=root
After connecting the database, we will be installing the UI auth package for the Auth Scaffolding. Here, you can use Laravel Breeze or Laravel Jetstream too. Actually, I am going to just implement the Login with Twitter with the User Authentication. Hence, I have no need for advanced features like Jetstream to be implemented here.
Dynamic Email Configuration in Laravel 8 For Sending Email
Install UI Auth in Laravel 8 For Login with Twitter
This package will provide the basic user authentication with Login, Register functionality. We need only these features. Therefore, let’s hit the below command.
composer require laravel/ui
After hitting the above command, it will install initiate the Laravel UI package in the project.
Now, after installing this package, it will require to add the auth scaffolding. So, let’s add it quickly.
php artisan ui vue --auth
In the next step, for the front end dependencies, you will require to install npm.
npm install && npm run dev
After installing the npm, it will ask you to build the package dependencies. On the successful build, it will generate the CSS and js file for the layout design.
Laravel 8 Client Side Form Validation Using jQuery
Install Laravel Socialite Package
To install the socialite package, hit the below command.
composer require laravel/socialite
After installing the socialite package, let’s add it in the providers and aliases array.
Create RESTful APIs in Laravel 8 Using Sanctum Auth
Add Provider and Alias for Socialite Package
If you don’t want to import the package namespace directly inside your controller then you can create it’s alias. You will find this configuration in the config/app.php file.
'providers' => [
…
…
…
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
…
…
…
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
Once you done let’s move to the twitter developer console for getting the client id and client secret key.
Create and Configure App in Twitter Developer Account
For implementing the Twitter Login, you will have to create an app in Twitter Developer Console.
If your developer account is already approved then you can create a new app as showing below.
Give the app name and simply click on the Get Keys button. It will redirect you to the next page with the API key and the API Secret Key. Just copy the keys and go to the projects and app list. Here, you will have to enable 3-legged OAuth for setting the callback URL for the Twitter Login.
Now, come back to the Laravel application. Here, we will have to configure the API credentials in Laravel.
Create RESTful APIs in Laravel 8 Using Passport Auth
Configure Twitter App Credentials in Laravel
After copying the client id and client secret, these keys required to set in the services array. So, just move to the config/services.php and add the below snippet there. Please put the client id and client secret. In the place of client id, you got the API key in the Twitter app. Similarly, replace the client_secrent with API Secret Key. That’s all for the configuration.
'twitter' => [
'client_id' => 'TWITTER_APP_API_KEY',
'client_secret' => 'TWITTER_APP_API_SECRET',
'redirect' => 'http://localhost:8000/auth/twitter-callback',
],
For storing the login user detail, we have to add one column for the twitter id in the users migration table.
Add Column in Users Migration Table
For adding the 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
Once the migration is created, let’s put one column there and then we 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');
});
}
}
Now, hit the migrate command to migrate the tables.
php artisan migrate
After the migration, you will see the tables are migrated properly. Now, in the next step, we have to add this fillable data in the model.
<?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 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',
];
}
Create Controller For Login With Twitter
php artisan make:controller SocialAuthController
After creating the controller, let’s add the below code for login functionality.
<?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());
}
}
}
After that you have to add routes for the above functions.
How to Upload Image in CKEditor 5 Using Laravel 8
Add Routes For Login With Twitter
Open the web.php file and add the below routes there.
Route::get('twitter', [SocialiteAuthController::class, 'twitterRedirect'])->name('auth/twitter');
Route::get('/auth/twitter-callback', [SocialiteAuthController::class, 'loginWithTwitter']);
Now, at last, we have to add a new button in the login.blade.php file for the Twitter login.
Add a Button in Login Page For Twitter Login
In the views/auth folder, you will find the login.blade.php file. So, just open it and add a button for the Twitter login. Also, set the redirect URL to the twitter as showing below.
@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="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail 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="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('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="form-group row">
<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="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-secondary">
{{ __('Login') }}
</button>
<a href="{{ route('auth/twitter') }}" class="btn btn-primary">
{{ __('Login with Twitter') }}
</a>
</div>
<div class="col-md-8 offset-md-4">
@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
Now, we are done, just check the result in the browser.
How to Create and Use Database Seeder in Laravel 8
Twitter Login Result in Laravel 8
After running the application, you will see there is the Auth Scaffolding. Here, you got the options of Login and Register. When clicking on the Login button, it will redirect you to the login.blade.php file.
As a result, when you will click on the Login, it will redirect you to the login page.
After clicking on the Login with Twitter button, it will redirecting to the authenticate with auth token.
After the successful authentication, it will redirect back to the callback URL. So, in our case, I have set the callback URL to the dashboard page.
Conclusion
By using the socialite package, we have implemented the Login with Twitter functionality. We installed the socialite package, configure the Twitter app and got the API key along with the secret key. After the keys configuration, we redirected to the twitter login. The Twitter login authentication is based on the OAuth. At last, after the successful login, it will redirect to the callback URL. So, this is not much complex steps to implement. But, in case, if you get any error then you can ask me through the comment section. I will help you for the same.
Leave a Reply