Blog Detail

10

Dec
Easily Integrate Twitter  API in Laravel with atymic/twitter cover image

arrow_back Easily Integrate Twitter API in Laravel with atymic/twitter

atymic/twitter is a package that provides Twitter API for Laravel 6.x, 7.x, 8.x (and new versions as they are released). It also supports other frameworks via PHP-DI. Before installing this package, you need to create an application and create your access token in the Application Management.

Installation

You’ve to run this command for the installation via Composer.

composer require atymic/twitter

Laravel Configuration

Just set the below environment variables in your .env.

TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET=
TWITTER_API_VERSION=

Advanced Laravel configuration

Next, you’ve to publish the config file. Just run this command.

php artisan vendor:publish --provider="Atymic\Twitter\ServiceProvider\LaravelServiceProvider"

It will create a file /config/twitter.php

Usage

Output format

You can choose between three different output formats. By default, responses will be returned as objects. To change this, use the format option in the parameters you pass to any method.

format : object|json|array (default:object)

Helper Functions

Linkify : Transforms URLs, @usernames, hashtags into links. The type of $tweet can be object, array or text. By sending an object or an array the method will expand links (t.co) too.

Twitter::linkify($tweet);

Ago : Converts date into difference (2 hours ago)

Twitter::ago($timestamp);

LinkUser : Generates a link to a specific user, by their user object (such as $tweet->user), or id/string.

Twitter::linkUser($user);

LinkTweet : Generates a link to a specific tweet.

Twitter::linkTweet($tweet);

Twitter API Versions

To set the default Twitter API version to v2 instead of the default v1.1, you can set the TWITTER_API_VERSION to 2 in your .env.

If you have set the v1.1 api as the default, you can use Twitter::forApiV2() to get an instance of the v2 client. The same goes for getting a v1 instance from a v2 client, using Twitter::forApiV1().

It is safe to call Twitter::forApiV1() on either a v1 or v2 client instance.

Functions

You can visit these links to view the function of v1 & v2 of Twitter API.

This package has detailed documentation about the integration of Twitter API in Laravel, For more details, you can head over to its documentation on Github.

Published at : 10-12-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project