KodeInfo | Learning resources for web and mobile development

Working with Twitter API's using Laravel

December 18th, 2014 17:20:01 in Artisan CLI , Configuration , Installation , Introduction , Packages , Laravel Tips by Imran Iqbal Comments(0) - Views(10788)
Tags : laravel, Twitter API, Hashtag, User Timeline, routes, Packages, composer

Till now we saw how we can work with on different components of Laravel framework in our previous tutorials. Let's get into some real coding part using Laravel framework. Twitter provide access to lots of data using different Twitter API's with their method signatures in their developer community website. Let's see how we can use twitter api's to post a tweet, getting a user timeline of tweets or getting tweets based on a hashtag.

Let's go deeper into laravel developer community, we don't need to write lot of code for this because there were already few packages in the community to handle dealing with Twitter API using Laravel. The one that really good was by https://twitter.com/thujohn. If we simply follow the steps provided in his documentation, we will be super fast in interacting with the Twitter API!. let's check it out.

Create a Twitter Application

First step to work with Twitter API, we need to create a twitter application at https://apps.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 thing why we are creating this application in twitter that we need an API Key, API secret, Access token and Access token secret. Don't share these things with anyone. Let's see steps in creating twitter application and once application registration successful, we need to generate access token like in third screen shot below.

Step 1



Now twitter application added successfully. We have to generate access token using the button provided under Keys and Access Tokens.

Now we successfully had all the keys and access token required from twitter application. Let's go into what we have to don on Laravel framework for this.

Laravel Twitter Package Installation

Now let's create a new project using laravel artisan command with name twitter by assuming you have already installed composer. If not please check our previous tutorials about how to install laravel.

composer create laravel/laravel twitter

Now we have to get copy of thujohn's package using composer  by including in composer.json file like below.

 "require": {
                "laravel/framework": "4.2.*",
                "thujohn/twitter": "dev-master"

Once after we added the package under required items in composer.json file. We just have to save and need to update composer using composer update command. So that it can fetch all the dependencies for that package.

After this we have to configure our providers and array aliases in app/config/app.php file like below.

'providers' => array(

'aliases' => array(

		'App'               => 'Illuminate\Support\Facades\App',
		'Artisan'           => 'Illuminate\Support\Facades\Artisan',
		'Auth'              => 'Illuminate\Support\Facades\Auth',
		'Blade'             => 'Illuminate\Support\Facades\Blade',
		'Cache'             => 'Illuminate\Support\Facades\Cache',
		'ClassLoader'       => 'Illuminate\Support\ClassLoader',
		'Config'            => 'Illuminate\Support\Facades\Config',
		'Controller'        => 'Illuminate\Routing\Controller',
		'Cookie'            => 'Illuminate\Support\Facades\Cookie',
		'Crypt'             => 'Illuminate\Support\Facades\Crypt',
		'DB'                => 'Illuminate\Support\Facades\DB',
		'Eloquent'          => 'Illuminate\Database\Eloquent\Model',
		'Event'             => 'Illuminate\Support\Facades\Event',
		'File'              => 'Illuminate\Support\Facades\File',
		'Form'              => 'Illuminate\Support\Facades\Form',
		'Hash'              => 'Illuminate\Support\Facades\Hash',
		'HTML'              => 'Illuminate\Support\Facades\HTML',
		'Input'             => 'Illuminate\Support\Facades\Input',
		'Lang'              => 'Illuminate\Support\Facades\Lang',
		'Log'               => 'Illuminate\Support\Facades\Log',
		'Mail'              => 'Illuminate\Support\Facades\Mail',
		'Paginator'         => 'Illuminate\Support\Facades\Paginator',
		'Password'          => 'Illuminate\Support\Facades\Password',
		'Queue'             => 'Illuminate\Support\Facades\Queue',
		'Redirect'          => 'Illuminate\Support\Facades\Redirect',
		'Redis'             => 'Illuminate\Support\Facades\Redis',
		'Request'           => 'Illuminate\Support\Facades\Request',
		'Response'          => 'Illuminate\Support\Facades\Response',
		'Route'             => 'Illuminate\Support\Facades\Route',
		'Schema'            => 'Illuminate\Support\Facades\Schema',
		'Seeder'            => 'Illuminate\Database\Seeder',
		'Session'           => 'Illuminate\Support\Facades\Session',
		'SoftDeletingTrait' => 'Illuminate\Database\Eloquent\SoftDeletingTrait',
		'SSH'               => 'Illuminate\Support\Facades\SSH',
		'Str'               => 'Illuminate\Support\Str',
		'URL'               => 'Illuminate\Support\Facades\URL',
		'Validator'         => 'Illuminate\Support\Facades\Validator',
		'View'              => 'Illuminate\Support\Facades\View',
                'Twitter'           => 'Thujohn\Twitter\TwitterFacade',

Generate a Twitter config file

Now we can easily generate a config file using the artisan command php artisan config:publish thjohn/twitter and it will generate a config file at app/config/packages/thujohn/twitter/config.php location. It looks like below one

// You can find the keys here : https://dev.twitter.com/

return array(
        'API_URL'             => 'api.twitter.com',
        'API_VERSION'         => '1.1',
        'AUTHENTICATE_URL'    => 'https://api.twitter.com/oauth/authenticate',
        'AUTHORIZE_URL'       => 'https://api.twitter.com/oauth/authorize',
        'ACCESS_TOKEN_URL'    => 'oauth/access_token',
        'REQUEST_TOKEN_URL'   => 'oauth/request_token',
        'USE_SSL'             => true,

        'CONSUMER_KEY'        => 'Consumer Key',
        'CONSUMER_SECRET'     => 'Consumer Secret',
        'ACCESS_TOKEN'        => 'Access Token',
        'ACCESS_TOKEN_SECRET' => 'AccessToken Secret',

Note that we have to list the above keys from our twitter application here to gain access to Twitter API's.

Post a Tweet

Now all of the setup work done. We can take our new laravel twitter application to access different Twitter API's to do some real actions. First let's see how we can post a tweet from here onto our twitter profile.

Let's write a simple route in our /app/routes.php file like below.

Route::get('/', function()
        return Twitter::postTweet(array('status' => 'This is my tweet from my new laravel twitter application', 'format' => 'json'));

After this we have to run the above route using our browser and instantly it will post the tweet on our timeline. It will also return a json response.

{"created_at":"Thu Dec 18 17:05:05 +0000 2014","id":545625813970731008,"id_str":"545625813970731008","text":"Tweet sent using Laravel and the Twitter API!","source":"\u003ca href=\"http:\/\/www.shoppingmakesmehappy.com\/\" rel=\"nofollow\"\u003eShoppingMakesMeHappy\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":138719163,"id_str":"138719163","name":"Venkata Krishna","screen_name":"venkatiiitb","location":"Hyderabad","profile_location":null,"description":"Senior Web Developer@Igenero","url":"http:\/\/t.co\/BnOouqUJ5D","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/BnOouqUJ5D","expanded_url":"http:\/\/code2firm.com","display_url":"code2firm.com","indices":[0,22]}]},"description":{"urls":[]}},"protected":true,"followers_count":21,"friends_count":17,"listed_count":0,"created_at":"Fri Apr 30 11:22:01 +0000 2010","favourites_count":1,"utc_offset":19800,"time_zone":"Chennai","geo_enabled":true,"verified":false,"statuses_count":100,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"EDECE9","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme3\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme3\/bg.gif","profile_background_tile":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/3490296249\/ceffdefadd096c745d521cfc999b62ad_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/3490296249\/ceffdefadd096c745d521cfc999b62ad_normal.jpeg","profile_link_color":"088253","profile_sidebar_border_color":"FFFFFF","profile_sidebar_fill_color":"E3E2DE","profile_text_color":"634047","profile_use_background_image":false,"default_profile":false,"default_profile_image":false,"following":false,"follow_request_sent":false,"notifications":false},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"symbols":[],"user_mentions":[],"urls":[]},"favorited":false,"retweeted":false,"lang":"en"}

Many More Methods

Now we saw how easy it was to configure a laravel application to post a tweet on our timeline in Twitter. It's good to check this library in github. Now let's see different other methods below.

To get recent tweets posted by the user by the screen_name and user_id parameters.

Route::get('/', function()
    return Twitter::getUserTimeline(array('screen_name' => 'thujohn', 'count' => 20, 'format' => 'json'));

To return most recent tweets and retweets posted by the authenticating user and the users they follow.

Route::get('/', function()
    return Twitter::getHomeTimeline(array('count' => 20, 'format' => 'json'));

To return X most recent mentions for a user in tweets by other users with his @screen_name

Route::get('/', function()
    return Twitter::getMentionsTimeline(array('count' => 20, 'format' => 'json'));


There are lot of other methods in this library please check it out in github link which is mentioned above. 


Kode Info


  • Imran Iqbal
    Imran Iqbal

    Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.



read more


read more


read more


read more

comments powered by Disqus