AppDividend
Latest Code Tutorials

Laravel Twitter Login Example | Laravel Twitter Socialite Login

7

Laravel Twitter Login Example is the tutorial title today we will deep dive.  I am going to show you how to do Twitter Login. We will use the Laravel Socialite composer package to use the Twitter API. The socialite is a package that makes building authentification with traditional social networks simple.

Overview Of Laravel Twitter Login

  • Step 1: Install and configure Laravel 6.
  • Step 2: Configure Laravel Auth.
  • Step 3: Install Laravel socialite package using componser require command.
  • Step 4: Create a Twitter app and acquire the token.
  • Step 5: Make a controller file.
  • Step 6: Create a Laravel view file for the form.
  • Step 7: Create a Laravel model.
  • Step 8: Create Laravel relationships between different models.
  • Step 9: Create a callback function that handles the application request.

Let’s start our Login with Twitter in Laravel example from scratch.

Step 1: Create a Laravel project.

Type the following command in your terminal.

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

Go to that project and start the Laravel server by typing the following command.

php artisan serve

The server starts at URL: http://localhost:8000

You need to configure your database in the .env file.

Type following command to run the migration files and that will create two database tables.

php artisan migrate

Step 2: Laravel authentication.

Laravel provides us basic authentication. It makes authentication painless. You just need to run the following command.

php artisan make:auth

It will create a route for us, and the code is following.

<?php 

// web.php

Auth::routes();

Go to the URL: http://localhost:8000/login

Do not forget to start your server by the following command.

php artisan serve

Step: 3 Require the laravel socialite package.

The socialite is a package that makes building authentification with traditional social networks simple. So we are using this Laravel specific package.

composer require laravel/socialite

Now, add the service provider to the config/app.php file.

<?php

// app.php

'providers' => [
    // Other service providers...

    Laravel\Socialite\SocialiteServiceProvider::class,
],

Moreover, also update an alias array

<?php

// app.php

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

Step 4: Create a Twitter App To Get Tokens.

Go to the Twitter developers portal by following URL: https://apps.twitter.com/

Login via your Twitter account. You will see this page.

Using Twitter Authentication For Login in Laravel 5

 

Click Create New App button. So click that button, and you will find a page like this.

Laravel 5.4 Socialite Twitter Login

 

Here, I have put my app name, description, website name, and callback URL on this page.

Note:  For you to be able to use this URL on your machine, you will have to run your Laravel app either in your virtual host or use Vagrant for your windows PC or Laravel Valet for your Mac.

The Website URL may be any placeholder URL if you do not have a real URL.

You will see your dashboard. Now go to the Keys and Access Tokens section and then you will find your following keys.

Consumer Key (API Key): XXXX

Consumer Secret (API Secret): XXXX

Now, take both of them and switch to your editor.

Navigate to the config  >>  services.php file and put one another services array by the following code.

Your Consumer Key becomes your client_id, and Consumer Secret becomes client_secret

<?php

'twitter' => [
    'client_id' => 'XXXX',
    'client_secret' => 'XXXX',
    'redirect' => '',
    ],

Step 5: Create one controller file for Laravel Socialite Auth.

Now, we need to create one controller, which handles the Twitter Authentication routes.

php artisan make:controller SocialAuthTwitterController

We need to create two methods in this controller, which are the following.

1)redirect():  Redirect our users to Twitter.

2) callback():  Handle callback from Twitter.

<?php

// SocialAuthTwitterController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Socialite;

class SocialAuthTwitterController extends Controller
{
  /**
   * Create a redirect method to twitter api.
   *
   * @return void
   */
    public function redirect()
    {
        return Socialite::driver('twitter')->redirect();
    }

    /**
     * Return a callback method from twitter api.
     *
     * @return callback URL from twitter
     */
    public function callback()
    {
       
    }
}

The next step would be to the routes >> web.php file and register the routes.

<?php

//web.php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/redirect', 'SocialAuthTwitterController@redirect');
Route::get('/callback', 'SocialAuthTwitterController@callback');

Route::get('/home', 'HomeController@index')->name('home');

Go to the config  >>  services.php file and update the twitter  redirect key and put the value ‘http://localhost:8000/callback.’

<?php

// services.php

'twitter' => [
    'client_id' => 'xxxxxxx',
    'client_secret' => 'xxxxxxx',
    'redirect' => 'http://localhost:8000/callback',
],

Step 6: Make one blade file and put one button Login with Twitter.

The next step would be, we just need to add the link to our route which will further redirect to Twitter.

So go to the resources  >>  views  >>  auth  >>  login.blade.php and add one link like Login with Twitter.

<!-- login.blade.php -->

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Login</div>
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="{{ route('login') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>

                                <a class="btn btn-link" href="{{ route('password.request') }}">
                                    Forgot Your Password?
                                </a>
                            </div>
                        </div>
                        <br />
                        <p style="margin-left:265px">OR</p>
                        <br />
                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                              <a href="{{url('/redirect')}}" class="btn btn-primary">Login with Twitter</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection




Now, if you have not started the server, then launch the server and go the following URL.

http://localhost:8000/login

Try to Laravel Twitter Login,  if everything sets up correctly.

Step 7: Create one model for Twitter Login Account.

Now, we are integrating our Twitter user in our Laravel application. Create one model as well as one migration in our app.

php artisan make:model SocialTwitterAccount -m

Now, add the following code in the create_social_twitter_accounts_table.php file. I am putting my final file in here.

<?php

// create_social_twitter_accounts.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSocialTwitterAccountsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('social_twitter_accounts', function (Blueprint $table) {
          $table->integer('user_id');
          $table->string('provider_user_id');
          $table->string('provider');
          $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('social_twitter_accounts');
    }
}

Run the following command if you have migrated previous tables.

php artisan migrate:refresh

Alternatively, you can use this command for the first time migration.

php artisan migrate

Step 8: Provide relations to that model.

The column provider_user_id is Twitter’s user id, and in provider, this case will always be Twitter

Add relations and fillable to the  SocialTwitterAccount model.

<?php

// SocialTwitterAccount.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SocialTwitterAccount extends Model
{
  protected $fillable = ['user_id', 'provider_user_id', 'provider'];

  public function user()
  {
      return $this->belongsTo(User::class);
  }
}

The next step would be some handling service that will try to register the user or login if the account already exists. Create folder app/Services.

Laravel has not any Services folder in the app directory so create a directory first and put the following content in that SocialTwitterAccountService.php file. So our full directory structure would look like this.

app  >>  Services >> SocialTwitterAccountService.php

<?php

namespace App\Services;
use App\SocialTwitterAccount;
use App\User;
use Laravel\Socialite\Contracts\User as ProviderUser;

class SocialTwitterAccountService
{
    public function createOrGetUser(ProviderUser $providerUser)
    {
        $account = SocialTwitterAccount::whereProvider('twitter')
            ->whereProviderUserId($providerUser->getId())
            ->first();

        if ($account) {
            return $account->user;
        } else {

            $account = new SocialTwitterAccount([
                'provider_user_id' => $providerUser->getId(),
                'provider' => 'twitter'
            ]);

            $user = User::whereEmail($providerUser->getEmail())->first();

            if (!$user) {

                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName(),
                    'password' => md5(rand(1,10000)),
                ]);
            }

            $account->user()->associate($user);
            $account->save();

            return $user;
        }
    }
}

It will try to find the provider’s account in the system, and if it is not present, it will create a new user. This method will also try to associate the social account with the email address in case the user already has an account.

Note: Twitter API does not return emails. If you need to get the email of a user, you need to add your app to the set of whitelisted apps. 

I have whitelist my app to fetch the User’s email ID by following steps.

Go to your developers Twitter account and in that navigate to the settings tab.

Laravel Social Twitter Login

Here you need to provide Privacy Policy URL and Terms and Condition URL.

Then go to the Permissions tab and tick the checkbox Request email addresses from users and update the settings.

Step 9: Make one callback function.

The last step is to update the SocialAuthTwitterController’s callback() function.

<?php

// SocialAuthTwitterController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Socialite;
use App\Services\SocialTwitterAccountService;

class SocialAuthTwitterController extends Controller
{
  /**
   * Create a redirect method to twitter api.
   *
   * @return void
   */
    public function redirect()
    {
        return Socialite::driver('twitter')->redirect();
    }

    /**
     * Return a callback method from twitter api.
     *
     * @return callback URL from twitter
     */
    public function callback(SocialTwitterAccountService $service)
    {
        $user = $service->createOrGetUser(Socialite::driver('twitter')->user());
        auth()->login($user);
        return redirect()->to('/home');
    }
}

All the coding is now finally complete. Go to the login URL of our application.

http://localhost:8000/login

Laravel 5.4 Twitter Login

Now, if you click on Login With Twitter button

Laravel 5.4 Social Sign In

Provide your twitter username and password. Now, you will see the following page.

Laravel 5.4 Socialite Tutorial

 

Finally, Laravel Twitter Login Example | Laravel Twitter Socialite Login Tutorial is Over.

Do Feedback this Tutorial via comment.

Github Code: https://github.com/KrunalLathiya/LaravelTwitterLogin

Steps To Use This Code: 
  1. Clone the repository in your local.
  2. Go to the root of the project and run command “composer update.“
  3. Edit .env file and use your MySQL database credentials.
  4. Configure developers twitter account get client_id and client_secret and also put your Web URL.
  5. Run the command “php artisan migrate.“
  6. Now, we need to bootstrap Laravel server so run “php artisan serve.“
  7. If now go to this URL: http://localhost:8000/login

Doubt?? ask in a comment below, I am happy to help you out.

7 Comments
  1. Jonas says

    Thanks.

    Why include the provider column in the social_twitter_accounts table when you already named the table in such manner that it’s already provider specific?

    1. Krunal says

      Actually, I have to provide specifics because sometimes there are more than one social logins and it’s best practice to give one column provider. Here I am using only one social login but still best practice to make one column for that.

  2. Mfawa Alfred Onen says

    Good tutorial but you need to update SocialTwitterAccountService to use bcrypt() or the Hash::make() Facade for the passwords as a better option.

  3. olivedev says

    Socialite is a great package in Laravel for easily implementing social login. My friend has written a similar article on it as well, but he has also explained adding Facebook login using socialite in laravel app.

    1. Krunal says

      I have also written how to log in with facebook in Laravel. Please check it. You find it useful

  4. Aymen says

    Thanks

  5. pid907455 says

    Промойте в нем обувь, в которойработали.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.