Mohamed Benhida

admin@devma.net

December 15, 2017

Twitter Api In Laravel

Hey,

in this post we will talk about how can you use twitter api so you can tweet in the backend like just auto tweet when you add a new product or a new blog on your website.

First of all we need to install this package twitteroauth

composer require abraham/twitteroauth

Then we go to our laravel project on app folder then we add a new folder named Services where you can add the extra services used for you laravel project in the same folder Services we create another a new folder Twitter .

We create now a Twitter class inside this Twitter folder

For publishing a tweet we call the post method with 'statuses/update' as first parametre and the message that you want to write as second parametre

app/Services/Twitter/Twitter.php

<?php

namespace App\Services\Twitter;

use Abraham\TwitterOAuth\TwitterOAuth;

class Twitter
{
    protected $twitter;

    public function __construct(TwitterOAuth $twitter)
    {
        $this->twitter = $twitter;
    }

    public function tweet(string $status)
    {

        return $this->twitter->post('statuses/update', compact('status'));
    }
}

Now we begin by creating a TwitterServiceProvider is where we initialize the twitter class that we just created with all the credentials for our Twitter API you can learn more here Bind Service Container

app/Services/Twitter/TwitterServiceProvider

<?php

namespace App\Services\Twitter;

use Abraham\TwitterOAuth\TwitterOAuth;
use Illuminate\Support\ServiceProvider;

class TwitterServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(Twitter::class, function () {
            $connection = new TwitterOAuth(
               config('services.twitter.consumer_key'),
               config('services.twitter.consumer_secret'),
               config('services.twitter.access_token'),
               config('services.twitter.access_token_secret')
           );

            return new Twitter($connection);
        });
    }
}

We go to config and we add those new services provided by Twitter API

config/services.php

'twitter' => [
        'consumer_key' => env('TWITTER_CONSUMER_KEY'),
        'consumer_secret' => env('TWITTER_CONSUMER_SECRET'),
        'access_token' => env('TWITTER_ACCESS_TOKEN'),
        'access_token_secret' => env('TWITTER_ACCESS_TOKEN_SECRET'),
    ],

on your .env file fill this with theire value

TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET=

We need to now to call the TwitterServiceProvider on the config/app.php so it can initialize each time with your project starts.

config/app.php

App\Services\Twitter\TwitterServiceProvider::class,

Now Let's make a simple example every time we added a post we need to tweet about it so here we will need a Post Model and a Laravel Job 

we begin by creating the Job php artisan make:job SendTweet

in this job we pass the post as a parametre so we can take the title,link and the tags related to this post

app/Jobs/SendTweet.php

<?php

namespace App\Jobs;

use App\Post;
use App\Services\Twitter\Twitter;
use App\Tag;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendTweet implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $post;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(Twitter $twitter)
    {
        $message = $this->toTweet($this->post);
        $twitter->tweet($message);
    }

    protected function toTweet(Post $post): string
    {
        $tags = $post->tags()
            ->map(function (Tag $tag) {
                return "#{$tag->name}";
            })
            ->implode(' ');

        return $post->title
            . PHP_EOL . $post->url
            . PHP_EOL . $tags;
    }
}

Now for tweeting we just need to call this job for tweeting SendTweet::dispatch($post);

We create our Post Model php artisan make:model Post -m

we add a save function (You really need to call the parent::save()) then we call the Job so every time you add a Post the job will trigger and it will tweet about it.

<?php

namespace App;

use App\Jobs\SendTweet;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   public function save(array $options = [])
    {
        parent::save();
        SendTweet::dispatch($this);
        
    }
}

I Hope you liked reading this post and it helped.

© Mohamed Benhida.

Blog | Packages | About