How to implement Twitter login in Laravel * DevRohit Think simplified

Rohit urane
4 min readMay 18, 2022

--

Hi guys,

Nowadays, users have less timespan on the website. In that case, we want to register a user on your platform. You should simplify the process of registration and login for your application. Laravel provides a socialite package to reduce the process, i.e., In minimum steps, they connect the user to your application. In this article, we implement a Twitter login to your application.

Step by step guide on Twitter login in the laravel application

Install Socialite package on laravel application. Run the following command.

composer require laravel/socialite

You need to add the below line of code inside the config/app.php file.

$providers= [ 
......
Laravel\Socialite\SocialiteServiceProvider::class,
......
];
$alias = [
......
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
......
]

On the Twitter platform, you need to apply for access and fill out the form. Click Here

You must create a project for getting API Key and API Secret Key. Afterward, you create an App for auth login. See the below Screenshots:-

Click Here To check

You can add credentials to the env file and add the environment variable on config/services.php against the twitter variable.

TWITTER_API_KEY=89fETSF1XXXXXXXXXXXX TWITTER_API_SECRET=j494USdWXD1gtwZvKmcxfXXXXXXXXXXXXXXXXX TWITTER_CALLBACK_URL=http://127.0.0.1:8000/auth/twitter

You can add the below code in the services.php file.

'twitter'=>[ 
'client_id' => env('TWITTER_API_KEY'),
'client_secret' => env('TWITTER_API_SECRET'),
'redirect'=> env('TWITTER_CALLBACK_URL')
]

Make a migration file that will create a column for the users’ table. Run migration command in your application.

<?php 
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddtwitterIdColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function ($table) {
$table->string('provider');
$table->string('provider_id')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropColumns('provider');
Schema::dropColumns('provider_id');
}
}

Run php artisan migrate command. Add fields to fillable property on the User.php file.

protected $fillable = [ 
'name',
'email',
'password',
'provider',
'provider_id'
];

Make a controller for social login. In your terminal, run:

php artisan make:controller SocialController

We are adding two methods: redirectToTwitter(), which redirects the user to Twitter to authorize the site, and handleTwitterCallback(), which handles the user’s credentials when called back from Twitter. We load the social driver’s social login. Here, I am loading a Twitter driver.

<?php 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use Inertia\Inertia;
use Illuminate\Support\Facades\Route;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class SocialController extends Controller
{
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleCallback($provider)
{
try {
// Get the user's information from social media
$socialmediaInfo = Socialite::driver($provider)->user();
// Find in Database
$finduser = User::where('provider_id', $user->id)->first();
if($finduser){
Auth::login($finduser);
return redirect('/');
}else{
$checkUser = User::where('email', $user->email)->first();
if($checkUser) {
$checkUser->provider = $provider;
$checkUser->provider_id = $socialmediaInfo->id;
$checkUser->save();
Auth::login($checkUser);
} else {
$newUser = User::create([
'name' => $user->name,
'email' => $user->email,
'provider'=> $provider,
'provider_id'=> $socialmediaInfo->id,
'password' => Hash::make('123456dummy')
]);
Auth::login($newUser);
}
return redirect('/');
}
} catch (Exception $e)
{
return Inertia::render('Auth/Login', [
'canResetPassword' => Route::has('password.request'),
'status' => 'Something Went wrong!! Try later',
]);
}
}
}

You need to define a route for social login in the route/web.php file.

Route::get('auth/{provider}', [SocialController::class, 'redirectToProvider']); 
Route::get('auth/{provider}/callback', [SocialController::class, 'handleCallback']);

Open resources/views/auth/login.blade.php. Add the below code and change the button style according to your application UI.

<div class="form-group"> 
<div class="col-md-8 col-md-offset-4">
<a href="{{url('/auth/twitter')}}" class="btn btn-secondary">Login with Twitter</a>
</div>
</div>

Finally Done ✔️

Now we have successfully integrated Twitter login into your application. We can check our social login. Socialite supports authentication via Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket. Go to the application login page and click on the login with Twitter button. It redirected the user to the GitHub authorization page. The user authorizes the application, and it will redirect to the dashboard page. If you have any questions, please leave a comment and I will respond as soon as possible.

Thank you for reading this article. Please share this article with your friend circle. That’s it for the day. Stay Connected!
Cheers

Originally published at https://www.devrohit.com on May 18, 2022.

--

--

Rohit urane
Rohit urane

Written by Rohit urane

enthusiastic full stack developer to build application

No responses yet