Login with Twitter in Laravel 9 Using Laravel Socialite

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

In 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * 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

1
2
3
4
5
6
7
8
9
10
11
/**
 * 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.

1
2
3
<a href="{{ url('/login/twitter') }}">
    {{ __('Login with Twitter') }}
</a>

I am calling this view from the index method of LoginController Class.

1
2
3
4
5
6
7
/**
 * Call the view
 */
public function index()
{
    return view('login');
}

Next, add some routes which will be required for the next part of the tutorial.

1
2
3
4
5
6
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 Twitter configuration array as follows:

1
2
3
4
5
'twitter' => [
    'client_id' => env('TWITTER_API_KEY'),
    'client_secret' => env('TWITTER_API_SECRET_KEY'),
    'redirect' => env('TWITTER_CALLBACK_URL'),
],

Hello Brother, env method is used to get the values of specified constants. It means we need to add these constants in the .env file.

1
2
3
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() : Inititates a OAuth flow and responsible to redirect users on login page of Twitter.
  • handleProviderCallback() : When user come back to application after login, get the user details and log the user in.
  • findOrCreateUser() : Insert the user entries to the database.

LoginController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?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.

Recent Posts

Related Posts