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' => [
'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.
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
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.