Laravel is lots of fun. Twitter is lots of fun. Why not create a quick example of how we can configure a super basic application to send a tweet using Laravel? Sounds like a good idea to me, so that is exactly what we will do right now. Now there are already a few packages in the community to handle dealing with the Twitter API using Laravel. The one that really stood out was by https://twitter.com/thujohn. If you simply follow the steps provided in his documentation, you’ll be blown away at how fast you will be interacting with the Twitter API! Let’s check it out.
Create a Twitter Application
First off, you will need to create a twitter application at https://dev.twitter.com/. Don’t worry, it’s really easy to do, just sign in with your twitter account and fill in the requested information. The main idea here is that you are going to need an API key, API secret, Access token, and Access token secret. The first two represent your new application, the second two represent your actual twitter account. Keep all of these a secret!
Get the Laravel Twitter Library
To get a copy of thujohn’s great library, simply include it in your composer.json file. My require block looks like this currently:
1 2 3 4 5 |
"require": { "laravel/framework": "4.2.*", "way/generators": "dev-master", "thujohn/twitter": "dev-master" }, |
Once you have your composer.json updated and saved, run composer update from the command line and you’ll see all of your dependencies pulled in.
Configure Your Providers and Aliases for Twitter
There are just a couple of things to update within your Laravel Application to get it ready to interact with the Twitter API. First we need to update the providers array. For this, just go to app/config/app.php
and add the entry for the Twitter Service Provider. My updated array looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
'providers' => array( 'IlluminateFoundationProvidersArtisanServiceProvider', 'IlluminateAuthAuthServiceProvider', 'IlluminateCacheCacheServiceProvider', 'IlluminateSessionCommandsServiceProvider', 'IlluminateFoundationProvidersConsoleSupportServiceProvider', 'IlluminateRoutingControllerServiceProvider', 'IlluminateCookieCookieServiceProvider', 'IlluminateDatabaseDatabaseServiceProvider', 'IlluminateEncryptionEncryptionServiceProvider', 'IlluminateFilesystemFilesystemServiceProvider', 'IlluminateHashingHashServiceProvider', 'IlluminateHtmlHtmlServiceProvider', 'IlluminateLogLogServiceProvider', 'IlluminateMailMailServiceProvider', 'IlluminateDatabaseMigrationServiceProvider', 'IlluminatePaginationPaginationServiceProvider', 'IlluminateQueueQueueServiceProvider', 'IlluminateRedisRedisServiceProvider', 'IlluminateRemoteRemoteServiceProvider', 'IlluminateAuthRemindersReminderServiceProvider', 'IlluminateDatabaseSeedServiceProvider', 'IlluminateSessionSessionServiceProvider', 'IlluminateTranslationTranslationServiceProvider', 'IlluminateValidationValidationServiceProvider', 'IlluminateViewViewServiceProvider', 'IlluminateWorkbenchWorkbenchServiceProvider', 'WayGeneratorsGeneratorsServiceProvider', 'ThujohnTwitterTwitterServiceProvider', ), |
We’ll also need to update the aliases array like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
'aliases' => array( 'App' => 'IlluminateSupportFacadesApp', 'Artisan' => 'IlluminateSupportFacadesArtisan', 'Auth' => 'IlluminateSupportFacadesAuth', 'Blade' => 'IlluminateSupportFacadesBlade', 'Cache' => 'IlluminateSupportFacadesCache', 'ClassLoader' => 'IlluminateSupportClassLoader', 'Config' => 'IlluminateSupportFacadesConfig', 'Controller' => 'IlluminateRoutingController', 'Cookie' => 'IlluminateSupportFacadesCookie', 'Crypt' => 'IlluminateSupportFacadesCrypt', 'DB' => 'IlluminateSupportFacadesDB', 'Eloquent' => 'IlluminateDatabaseEloquentModel', 'Event' => 'IlluminateSupportFacadesEvent', 'File' => 'IlluminateSupportFacadesFile', 'Form' => 'IlluminateSupportFacadesForm', 'Hash' => 'IlluminateSupportFacadesHash', 'HTML' => 'IlluminateSupportFacadesHTML', 'Input' => 'IlluminateSupportFacadesInput', 'Lang' => 'IlluminateSupportFacadesLang', 'Log' => 'IlluminateSupportFacadesLog', 'Mail' => 'IlluminateSupportFacadesMail', 'Paginator' => 'IlluminateSupportFacadesPaginator', 'Password' => 'IlluminateSupportFacadesPassword', 'Queue' => 'IlluminateSupportFacadesQueue', 'Redirect' => 'IlluminateSupportFacadesRedirect', 'Redis' => 'IlluminateSupportFacadesRedis', 'Request' => 'IlluminateSupportFacadesRequest', 'Response' => 'IlluminateSupportFacadesResponse', 'Route' => 'IlluminateSupportFacadesRoute', 'Schema' => 'IlluminateSupportFacadesSchema', 'Seeder' => 'IlluminateDatabaseSeeder', 'Session' => 'IlluminateSupportFacadesSession', 'SoftDeletingTrait' => 'IlluminateDatabaseEloquentSoftDeletingTrait', 'SSH' => 'IlluminateSupportFacadesSSH', 'Str' => 'IlluminateSupportStr', 'URL' => 'IlluminateSupportFacadesURL', 'Validator' => 'IlluminateSupportFacadesValidator', 'View' => 'IlluminateSupportFacadesView', 'Twitter' => 'ThujohnTwitterTwitterFacade', ), |
Generate a Config File
Now we can easily generate a config file using the command line. Simply run php artisan config:publish thujohn/twitter
and you will now find a new config file located at /app/config/packages/thujohn/twitter/config.php
. It looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php // You can find the keys here : https://dev.twitter.com/ return array( 'API_URL' => 'api.twitter.com', 'API_VERSION' => '1.1', 'USE_SSL' => true, 'CONSUMER_KEY' => 'API key', 'CONSUMER_SECRET' => 'API secret', 'ACCESS_TOKEN' => 'Access token', 'ACCESS_TOKEN_SECRET' => 'Access token secret', ); |
Note that these are the API key, API secret, Access token, and Access token secret you have listed in your app at the developer console on Twitter. Fill in these values with your own here in this config file.
Send a Tweet!
All of the legwork is now out of the way. We can take our new Laravel Twitter Application for a spin! We’ll start with the obligatory example from the routes file like so:
1 2 3 4 |
Route::get('/tweet', function() { return Twitter::postTweet(array('status' => 'Tweet sent using Laravel and the Twitter API!', 'format' => 'json')); }); |
Now, if we’ve done everything correctly, as soon as we hit that route, a tweet will be sent to Twitter with the status of “Tweet sent using Laravel and the Twitter API!” Let’s try.
Awesome! As you can see, it worked like a charm – with link direct to the tweet which was posted ๐
Many More Powerful Options
Now that we see just how easy it was to configure a Laravel Application to send messages to Twitter, I recommend you check out the source of this library here. We can see that the code has many, many great methods to use in the Facade Style of Laravel. As far as I can see, the entirety of the Twitter API is covered!
Now just to show how powerful this library is, we’ll set up a new route to getmytweets
, which will, you guessed it, fetch all of my tweets from the Twitter API. Now of course, in the real world, we would break all of this out in to controllers and views, but just to quickly demonstrate the power of this library, we’ll string together some of it’s commands for fun. We’ll make use of Twitter::getUserTimeline(), Twitter::linkify(), Twitter::linkUser(), Twitter::ago(), and Twitter::linkTweet(). With only these methods, we can fetch our timeline, linkify any links, username, or hashtags, link to the user who posted the tweet, display how long ago the tweet was posted, as well as provide a direct link to the tweet!
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Route::get('/getmytweets', function() { $tweets = Twitter::getUserTimeline(array('screen_name' => 'vegibit', 'count' => 20, 'format' => 'object')); foreach($tweets as $tweet){ echo '<b>Tweet Text:</b> '.Twitter::linkify($tweet->text).'<br>'; echo '<strong>Posted By:</strong> <a href="http:'.Twitter::linkUser($tweet->user). '">'.$tweet->user->name.'</a> <em>'.Twitter::ago($tweet->created_at).'</em><br>'; echo '<strong>Original Tweet:</strong> <a href="http:'.Twitter::linkTweet($tweet). '">http:'.Twitter::linkTweet($tweet).'</a><hr>'; } }); |
Check out the result:
Tweet Text: Top 12 Websites for Twitter Bootstrap http://t.co/vjS9PN0zHP #webdesign #websites
Posted By: vegibit 8 minutes ago
Original Tweet: http://twitter.com/vegibit/status/501414495961772032
Tweet Text: Tweet sent using Laravel and the Twitter API!
Posted By: vegibit 1 hour ago
Original Tweet: http://twitter.com/vegibit/status/501400060983140352
Tweet Text: Send Email With Laravel http://t.co/HLchjEtcSg
Posted By: vegibit 16 hours ago
Original Tweet: http://twitter.com/vegibit/status/501170512664350720
Tweet Text: This Is How To Make AJAX Awesome With jQuery http://t.co/ur2uhljeFR #jquery #ajax
Posted By: vegibit 20 hours ago
Original Tweet: http://twitter.com/vegibit/status/501112484443725824
Tweet Text: The Top 9 Most Important HTML Form Concepts You Should Master http://t.co/aqw4y2JuEP #html #webdevelopment
Posted By: vegibit 1 day ago
Original Tweet: http://twitter.com/vegibit/status/501052135354953729
Tweet Text: Top 12 Websites for Twitter Bootstrap http://t.co/1kZg5ksZy5
Posted By: vegibit 1 day ago
Original Tweet: http://twitter.com/vegibit/status/501040545011998723
Tweet Text: This Is How To Make AJAX Awesome With jQuery http://t.co/SOh2x8PoTE
Posted By: vegibit 1 day ago
Original Tweet: http://twitter.com/vegibit/status/501040206070308864
Tweet Text: Flash Messages in Laravel http://t.co/sPaqRlge36 #laravel #UI #UX
Posted By: vegibit 1 day ago
Original Tweet: http://twitter.com/vegibit/status/500750170213326848
Tweet Text: Laravel Eloquent ORM Tutorial http://t.co/CGKJSYGhaQ #php #webdev
Posted By: vegibit 2 days ago
Original Tweet: http://twitter.com/vegibit/status/500689720482209794
Tweet Text: JavaScript Operators and Expressions http://t.co/o8D4ThjJTv #JavaScript
Posted By: vegibit 2 days ago
Original Tweet: http://twitter.com/vegibit/status/500387763595014146
Tweet Text: 5 Classic Childhood Books To Read Again As An Adult http://t.co/J9JPzgwsPQ via @zolabooks
Posted By: vegibit 3 days ago
Original Tweet: http://twitter.com/vegibit/status/500327337888854016
Tweet Text: 3 Super-Actionable Keyword Research Tips to Try Right Now http://t.co/6EWRMdz2wP via @wordstream
Posted By: vegibit 3 days ago
Original Tweet: http://twitter.com/vegibit/status/500025341889753088
Tweet Text: From Startup to Rapid Growth: How SendGrid Scaled Their Developer Evangelist Strategy http://t.co/FBI7ouvwbc via @CMXSummit
Posted By: vegibit 4 days ago
Original Tweet: http://twitter.com/vegibit/status/499964970524999681
Tweet Text: RT @ozchrisrock: The five stages of waking up:
1. Denial
2. Bargaining
3. Stress
4. Depression
5. Coffee
Posted By: vegibit 4 days ago
Original Tweet: http://twitter.com/vegibit/status/499935647637856256
Tweet Text: The Top 9 Most Popular #JavaScript Frameworks http://t.co/Xf9H2O6cdx #WebDev
Posted By: vegibit 4 days ago
Original Tweet: http://twitter.com/vegibit/status/499622100928196609
Tweet Text: RT @LaravelWeekly: Be sure to subscribe to @laravelnews to stay up to date with weekly Laravel news while weโre away! #laravel
Posted By: vegibit 4 days ago
Original Tweet: http://twitter.com/vegibit/status/499620102376263681
Tweet Text: Twitter Bootstrap Series โ The 12 Column Grid http://t.co/0900XfsE9c #Bootstrap #twitter
Posted By: vegibit 4 days ago
Original Tweet: http://twitter.com/vegibit/status/499617690559193089
Tweet Text: What are Laravel Filters? http://t.co/rzdBAXlQIT #php #laravel
Posted By: vegibit 5 days ago
Original Tweet: http://twitter.com/vegibit/status/499343850755076099
Tweet Text: Everything You Need To Know About HTML Hyperlinks http://t.co/cwNJ7UmzNv #HTML #links
Posted By: vegibit 5 days ago
Original Tweet: http://twitter.com/vegibit/status/499255350164742144
Tweet Text: Join the Web Tutorials Community on Google+ http://t.co/JZh8PbRdtc #WebDesign #WebDevelopment #GooglePlus
Posted By: vegibit 6 days ago
Original Tweet: http://twitter.com/vegibit/status/499210889946341376
Conclusion
Using Laravel to work with the Twitter API is pretty easy when you make use of the great libraries the community has come up with. This particular one seems to be just perfect, and feels like a direct extension of Laravel as everything is done in a Facade style. It really makes working with the Twitter API in Laravel a breeze. When you’re ready for a bigger challenge using this library, check out this tutorial done by Creative Punch, it’s fantastic!