Getting Your Tweets Twitter For Laravel Tutorial Part 1

Nov 21, 2016 twitter tweet api laravel tutorial
WhatsApp
It seems the majority of Twitter tutorials for Laravel (in particular) focus on logging the user in, adding their credentials to the database and then posting tweets to the user account. We’re going to skip the majority of that because I know you don’t have to log in to twitter but you can just supply your API keys to your Laravel App and begin posting, retrieving etc.

In this tutorial we’ll focus on setting up Twitter for your Laravel App and then using the correct API to access your tweets to post to your website!

First we’ll grab the library that we’ll be using to make things fast to set up. Here’s the link to the said library https://github.com/thujohn/twitter. He has also provided some examples and a short installation guide.

I had some trouble adding thujohn/twitter”: “~2.0” to my composer.json file, as it would not sync my packages properly. Use the command line to grab the library instead

composer require thujohn/twitter


Add the providers and aliases (he’s actually forgotten to add the class to the end of each I’ve added it below

'providers' => [
'Thujohn\Twitter\TwitterServiceProvider::class’,
]

'aliases' => [
'Twitter' => Thujohn\Twitter\Facades\Twitter::class,
]

Run ‘php artisan vendor:publish’ and in then in your .env file you’ll want to fill out the details from your twitter developer account.


TWITTER_CONSUMER_KEY =
TWITTER_CONSUMER_SECRET =
TWITTER_ACCESS_TOKEN =
TWITTER_ACCESS_TOKEN_SECRET =


Now we’re ready to call some Twitter API functions. We can setup a quick test route like so and call our last tweet we posted

Route::get('/twitterTest', function()
{
return Twitter::getUserTimeline(['screen_name' => ‘username’, 'count' => 1, 'format' => ‘object’]);
});

What you’ll have returned is an Array of tweet objects, because we’ve declared the format is an object. You can access them via index with the object’s member ‘text’ to grab the tweet’s text. Don’t forget to use var_dump() or dd() to print out the values.

If you found the following info helpful, I'm happy to accept any donations of the following cryptocurrencies.

  • Bitcoin - 17DTiPExzP9StqveW428acEyB4mVMfKbiK
  • Ethereum - 0x87B8307FD20dc90cc05c94905Ec593134D32B6FF
  • Litecoin - LZMiz5U5sVq9doMLYE3gfLJrxCQDKuyCmU
  • Neo - AXv71WB38ajc1KUUEnxQKhynLLPc4BapVb