In the past, I have published an article on Login with Twitter in PHP. One of our readers asked to write an article on login with Twitter in Laravel. Though Laravel is built on the top of PHP programming language I know that mentioned tutorial is not suitable for the Laravel framework. Laravel has its own standards, folder structure, and development flow. A developer should follow the standards of Laravel while building web applications in it.
Laravel releases a few official packages that help developers achieve certain functionality. One of the packages is Socialite. Using Laravel Socialite, one can integrate social login with different providers like Facebook, Twitter, LinkedIn, Google, etc. The focus of this tutorial is on Twitter and thus in this article, we study Login with Twitter in Laravel using Socialite.
Getting Started
Let’s start with the fresh Laravel installation. It’s not compulsory to use a new Laravel installation, you can also use your existing project.
For installing fresh Laravel, run the command below:
composer create-project --prefer-dist laravel/laravel twitterlogin
Upon installation, create the database and add its credentials to the .env
file. We are building a login system, so we need to store user details in the database.
When a user logged in with Twitter, we will get their unique Twitter id. To store this id I’ll add the columns provider
and provider_id
to the ‘users’ table. The column provider
will store the value as ‘twitter’ and a column provider_id
is for the user’s Twitter id.
As the user is using a social website for login, we don’t need a password. Our ‘password’ column should accept the ‘NULL’ value as default. Also, there is no guarantee of getting the user’s email so the ’email’ column would also accept the ‘NULL’ value.
Open the ‘users’ table migration file and add the code below.
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique()->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->string('provider');
$table->string('provider_id');
$table->rememberToken();
$table->timestamps();
});
}
Run the migration command which will create tables in your database.
php artisan migrate
Next, add the provider
and provider_id
columns to the User model.
app/Models/User.php
/**
* The attributes that are mass assignable.
*
* @var array
*/protected $fillable = [
'name',
'email',
'password',
'provider',
'provider_id',
];
Get Twitter Credentials
To interact with the Twitter APIs in the Laravel application, you need to get your Twitter API credentials. Follow the steps below to create a Twitter app and get your API keys.
- Log in to the Twitter developer account and create a new application.
- Fill up all required fields such as the application name and description.
- Add your website domain in the Website field.
- Set the callback URL as
http://localhost:8000/twitter/callback
. You can adjust this URL as per your requirement. - Once you have registered, copy the Consumer API Keys.
Using these copied credentials, your Laravel application will complete the OAuth flow with Twitter. The Socialite package handles this OAuth flow. All we need to do is follow their guidelines.
Create Routes and Controller
To create a login flow, let’s create a LoginController
with the command:
php artisan make:controller LoginController
After this, create a login.blade.php
and add the following HTML to it.
<a href="{{ url('/login/twitter') }}">
{{ __('Login with Twitter') }}
</a>
I am calling this view from the index
method of LoginController
Class.
/**
* Call the view
*/
public function index()
{
return view('login');
}
Next, add some routes which will be required for the next part of the tutorial.
Route::get('login', 'LoginController@index');
Route::get('login/{provider}', 'LoginController@redirectToProvider');
Route::get('{provider}/callback', 'LoginController@handleProviderCallback');
Route::get('/home', function () {
return 'User is logged in';
});
Once users login with Twitter, I will redirect them to the home
route. It’s just for demo purposes. You should change this route to something else.
Login with Twitter in Laravel
We have created a controller, routes, and view. Next, run the below command to install the Socialite package.
composer require laravel/socialite
Upon installing Socialite, we need to configure it. Open the config/services.php
and add the Twitter configuration array as follows:
'twitter' => [
'client_id' => env('TWITTER_API_KEY'),
'client_secret' => env('TWITTER_API_SECRET_KEY'),
'redirect' => env('TWITTER_CALLBACK_URL'),
],
Here, env
method is used to get the values of specified constants. It means we need to add these constants to the .env
file.
TWITTER_API_KEY=PASTE_TWITTER_API_KEY
TWITTER_API_SECRET_KEY=PASTE_TWITTER_API_SECRET_KEY
TWITTER_CALLBACK_URL=http://localhost:8000/twitter/callback
Make sure to replace the placeholders with actual API keys. Finally in the LoginController
, I am writing a few methods that redirect a user to Twitter for login, and on successful authentication, it will store the user’s information and log the user in.
redirectToProvider()
: Initiates an OAuth flow and is responsible to redirect users to login page of Twitter.handleProviderCallback()
: When the user comes back to the application after login, get the user details and log the user in.findOrCreateUser()
: Insert the user entries into the database.
LoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Socialite;
use App\Models\User;
use Auth;
class LoginController extends Controller
{
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Call the view
*/
public function index()
{
return view('login');
}
/**
* Redirect the user to the Twitter authentication page.
*
* @return Response
*/
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
/**
* Obtain the user information from Twitter.
*
* @return Response
*/
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
/**
* If a user has registered before using social auth, return the user
* else, create a new user object.
* @param $user Socialite user object
* @param $provider Social auth provider
* @return User
*/
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => $provider,
'provider_id' => $user->id
]);
}
}
Head over to the login route and click the ‘Login with Twitter’ link. Complete the authorization and you should log in to the system using Twitter. You may also find entries in the ‘users’ table.
If you are curious to see how Socialite handles this Twitter flow, check out the TwitterProvider.php
file which you may find inside the vendor/laravel/socialite
directory.
I hope you learned how to integrate login with Twitter in Laravel using the Socialite package. I would like to hear your thoughts and suggestions in the comment section below.
Related Articles
- Login with LinkedIn in Laravel Using Laravel Socialite
- Google Login in Laravel Using Laravel Socialite
- Google OAuth Login with PHP
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.