Automate Tweets on Twitter Using Laravel Queues/Jobs — codementor.tech
This is just a small explanation. If you want to read full specification please go through THIS link.
REGISTERING YOUR TWITTER APP :
Before you can do any actual coding, you need to register your app on Twitter, head over to the developer portal and create your app. The home page will show a list of your Twitter apps, if this is your first time then you won’t have any apps, click on create a new app.
Fill out all the mandatory fields then proceed you should see a screen that shows you your Consumer Key and Consumer Secret. Copy those down and also create some access tokens. These access tokens are for writing Twitter apps that only interact with your OWN account. Copy down the access token and the access token secret, and that’s all you have to do. Now let’s code!
Here is an image of my twitter developer app.
APPLICATION COMPONENTS :
Here, We are going to use Twitter API for Laravel for share on twitter. In this article, we are going to user Laravel Job Event.
Add thujohn/twitter using composer,
composer require thujohn/twitter
In the config/app.php make sure to add the following provider and alias,
'providers' => [
Thujohn\Twitter\TwitterServiceProvider::class,
]'aliases' => [
'Twitter' => Thujohn\Twitter\Facades\Twitter::class,
]
Lastly, run the following command to import the twitter config/ttwitter.php file and modify inserting your Twitter app credentials
php artisan vendor:publish --provider="Thujohn\Twitter\TwitterServiceProvider"
Here, We are going to share a simple user message or you can say only tweet user message.
After this, You can create your tweet model and controller as well. Here I have already a controller, and I don’t need a model because I don’t want to save content which is tweeted.
So first let’s create a job for that,
php artisan make:job ShareOnTwitter
Below is my code for ShareOnTwitter.php file,
use ProgrammingSchool\Core\Jobs\Job;
use ProgrammingSchool\User\Models\User;
use Twitter;class ShareOnTwitter extends Job
{
public function __construct(User $user)
{
$this->user = $user;
}
public function handle()
{
if ($this->user) {
//post the tweet
$status = $this->user->website; Twitter::postTweet(
['status' => $status, 'format' => 'json']
);
}
}
}
As you can see in above code, we will just tweet a user’s website.
Now, We will call ShareOnTwitter.php from a controller, or you can directly test it from php artisan tinker.
Here, I am going to test it from php artisan tinker. As shown below,
The Tweet model only has two attributes a string that holds the content that is limited to 140 characters and a timestamp for when you want the tweet to be published.
That’s It. Now you can automatically tweet your content through Laravel.
Cheers.
Happy Coding!