Login with Twitter in Laravel Using Laravel Socialite

Recently 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 PHP programming language and I wrote about Twitter login in PHP, I know that past tutorial is not suitable for the Laravel framework. Laravel has its own folder structure, development flow. A developer should follow the standards of Laravel while building web applications in it.

Laravel has its official packages which help developers to achieve certain functionality. One of the packages is Socialite. Using Socialite, you can integrate social login with different providers like Facebook, Twitter, LinkedIn, Google, etc.

In this article, we study Login with Twitter in Laravel using Laravel 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 latest Laravel, run the command below:

composer create-project --prefer-dist laravel/laravel twitterlogin

Upon installation, create the database and add the credentials in the .env file. We are building a login system so we should store user details in the database.

This tutorial is based on Sign in with Twitter so we will get the user’s Twitter id after successful authentication. To store this social id we are adding 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.

When we use social login we don’t need to store passwords so the password column should accept the ‘NULL’ value as default. There is no guarantee of getting the user’s email after social login so for curiosity we need to set email columns also to 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')->nullable();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password')->nullable();
        $table->string('provider');
        $table->string('provider_id');
        $table->rememberToken();
        $table->timestamps();
    });
}

After this run the migration command which will create tables in your database.

php artisan migrate

You also need to add the provider and provider_id columns to the User model.

app/User.php

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password', 'provider', 'provider_id'
];

Get Twitter Credentials

As we are going to integrate Twitter login in Laravel, you first need to get your Twitter credentials. Follow the steps below to create a Twitter app and get your credentials.

  • 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. Adjust the URL as per your requirement.
  • Once you have registered, copy, and paste the created application credentials (Consumer Key and Secret) which require in some time.
Twitter Credentials

Using these copied credentials, your Laravel application will complete OAuth flow when users sign in with their Twitter account.

Create Routes and Controller

In order to include the functionality of sign in with Twitter, we need to add a code in our Laravel project. Let’s create a LoginController using the command:

php artisan make:controller LoginController

We need to add a login link in the blade file. Create a login.blade.php and add the following HTML to it.

<a href="{{ url('/login/twitter') }}" class="btn btn-success">
    {{ __('Login with Twitter') }}
</a>

You can call this view from the index method of LoginController.

/**
 * Call the view
 */
public function index()
{
    return view('login');
}

Next, add the route for it. I am also adding few more routes which will be required for next part of 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';
});

After user will 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

It’s time to use the Socialite package now. Using the below command you can install the Socialite package to your Laravel project.

composer require laravel/socialite

After installing Socialite, we need to configure it. Open the config/services.php and add Twitter configuration to this file as follows:

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

You may notice I used the env method to get the specified values. It means we need to define these constants in 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 your actual API keys. Next in the LoginController, we are writing a function that redirects a user to the Twitter login page, and on successful authorization, it will log the user in.

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 page and click the ‘Login with Twitter’ link. Complete the process and you should log in to the system using Twitter. You may also find entries of users in the users table.

I hope you may learn about login with Twitter in Laravel using the Socialite package. I would like to hear your thoughts or suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

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