Laravel 5 Twitter Login Tutorial

Laravel 5 Twitter Login Tutorial is the tutorial title today we will deep dive. I am going to show you how to Login users with Twitter So let us start Laravel 5 Twitter Login Tutorial.

Step: 1

Create a Laravel project by following command in your terminal.

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

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

php artisan serve

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 Auth

Laravel 5.4 provides us basic authentication. It makes authentication painless. You just need to run 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

Laravel 5 Twitter Login Tutorial

The socialite is a package that makes building authentification with traditional social networks simple. So we are using this Laravel 5.4 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,

Create Twitter App To Get Tokens

Step: 4

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

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

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

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

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

1)redirect(): Redirect our users to the 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()
{

}
}

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

Next step would be, we just need to add the link to our route which will further redirect to the 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 Login via Twitter and if everything sets up correctly.

Step: 7

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

The column provider_user_id is Twitter's user id, and inprovider 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);
}
}

Next step would be some handling service that will try to register the user or login if the account already exists. Create folderapp/Services. Laravel 5.4 has not any Services folder in app directory so create a directory first and put 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 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 that 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.

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

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

Step: 9

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

Now, if you click on Login With Twitter button

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

Finally, Our Laravel 5 Twitter 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.
Originally published at appdividend.com on July 21, 2017.