Laravel Twitter API using Thujohn/twitter Tutorial

By Hardik Savani November 5, 2023 Category : PHP Laravel Bootstrap Twitter API

In this tutorial, I am going to share how to access twitter feed using twitter api in laravel 5, laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10. In this example we also post tweet with multiple image upload using thujohn/twitter composer package of Laravel.

As you know twitter is very popular social networking website. They also provide api to manage your tweets and also other information. In this example we are going to use thujohn/twitter composer package for use twitter api. thujohn/twitter package through we can use easily all api like fetch linkify(), linkUser(), getUserTimeline(), getHomeTimeline(), postTweet(), uploadMedia() etc. So today we will learn how to use this all method in your laravel application.

In this example i going to describe from scratch, so if you don't know how to use twitter api then also you can do it. You can also use this example in your all version on Laravel like laravel 5.0, laravel 5.1, laravel 5.2 and laravel 5.3. After finish this example you can access user time line tweets and also tweets with image uploading using api.

Step 1 : Install Laravel Application

This tutorial is from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Install Package

In this step we have to addthujohn/twitter package for twitter api method so one your cmd or terminal and fire bellow command:

composer require thujohn/twitter

After successfully install package, open config/app.php file and add service provider and alias.

config/app.php

'providers' => [

....

'Thujohn\Twitter\TwitterServiceProvider',

],

'aliases' => [

....

'Twitter' => 'Thujohn\Twitter\Facades\Twitter',

]

we have to also make public configuration file by following command, after run this command you will find config/ttwitter.php file. So run bellow command:

php artisan vendor:publish

Now we require to generate twitter api key, twitter api secret, twitter access token and twitter access token secret, So you can follow to twitter developer account link:

Twitter Dev

And then you have to create new variable in your .env file like as bellow:

.env

TWITTER_CONSUMER_KEY =

TWITTER_CONSUMER_SECRET =

TWITTER_ACCESS_TOKEN =

TWITTER_ACCESS_TOKEN_SECRET =

Step 3: Create Route

In this is step we need to create route for twitter posts feed layout file and another one for add new tweets post. so open your routes/web.php file and add following route.

routes/web.php

Route::get('twitterUserTimeLine', 'TwitterController@twitterUserTimeLine');

Route::post('tweet', ['as'=>'post.tweet','uses'=>'TwitterController@tweet']);

Step 4: Create Controller

In this point, now we should create new controller as TwitterController in this path app/Http/Controllers/TwitterController.php. this controller will manage layout and getting data request and return response after tweets, so put bellow content in controller file:

app/Http/Controllers/TwitterController.php

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Twitter;

use File;


class TwitterController extends Controller

{

/**

* Create a new controller instance.

*

* @return void

*/

public function twitterUserTimeLine()

{

$data = Twitter::getUserTimeline(['count' => 10, 'format' => 'array']);

return view('twitter',compact('data'));

}


/**

* Create a new controller instance.

*

* @return void

*/

public function tweet(Request $request)

{

$this->validate($request, [

'tweet' => 'required'

]);


$newTwitte = ['status' => $request->tweet];


if(!empty($request->images)){

foreach ($request->images as $key => $value) {

$uploaded_media = Twitter::uploadMedia(['media' => File::get($value->getRealPath())]);

if(!empty($uploaded_media)){

$newTwitte['media_ids'][$uploaded_media->media_id_string] = $uploaded_media->media_id_string;

}

}

}


$twitter = Twitter::postTweet($newTwitte);


return back();

}

}

Step 5: Create View

In Last step, let's create twitter.blade.php(resources/views/twitter.blade.php) for layout and we will write design code here and also form for add new tweet in twitter website, So put following code:

resources/views/twitter.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel 5 - Twitter API</title>

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

</head>

<body>


<div class="container">

<h2>Laravel 5 - Twitter API</h2>


<form method="POST" action="{{ route('post.tweet') }}" enctype="multipart/form-data">


{{ csrf_field() }}


@if(count($errors))

<div class="alert alert-danger">

<strong>Whoops!</strong> There were some problems with your input.

<br/>

<ul>

@foreach($errors->all() as $error)

<li>{{ $error }}</li>

@endforeach

</ul>

</div>

@endif


<div class="form-group">

<label>Add Tweet Text:</label>

<textarea class="form-control" name="tweet"></textarea>

</div>

<div class="form-group">

<label>Add Multiple Images:</label>

<input type="file" name="images[]" multiple class="form-control">

</div>

<div class="form-group">

<button class="btn btn-success">Add New Tweet</button>

</div>

</form>


<table class="table table-bordered">

<thead>

<tr>

<th width="50px">No</th>

<th>Twitter Id</th>

<th>Message</th>

<th>Images</th>

<th>Favorite</th>

<th>Retweet</th>

</tr>

</thead>

<tbody>

@if(!empty($data))

@foreach($data as $key => $value)

<tr>

<td>{{ ++$key }}</td>

<td>{{ $value['id'] }}</td>

<td>{{ $value['text'] }}</td>

<td>

@if(!empty($value['extended_entities']['media']))

@foreach($value['extended_entities']['media'] as $v)

<img src="{{ $v['media_url_https'] }}" style="width:100px;">

@endforeach

@endif

</td>

<td>{{ $value['favorite_count'] }}</td>

<td>{{ $value['retweet_count'] }}</td>

</tr>

@endforeach

@else

<tr>

<td colspan="6">There are no data.</td>

</tr>

@endif

</tbody>

</table>

</div>


</body>

</html>


Now we are ready to run our example so run bellow command ro quick run:

php artisan serve

Now you can open bellow url on your browser:

http://localhost:8000/twitterUserTimeLine

You can get more information about package from here : Click Here.

I hope it can help you...

Video

Shares