Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sahil1711's avatar

Using Birdelephant for posting on twitter.

Hey all, I am currently trying to integrate this library for posting tweets on X in one of the projects I am working. https://birdelephant.com/. I have created a XController and routes , however i am totally confused as to how to use it. Ideally the functionality i am creating for my users , would help to connect their twitter accounts, and let the app post on their behalf.

Here's where I am: `<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request; use Inertia\Inertia; use Session; use Coderjerk\BirdElephant\BirdElephant; use Coderjerk\BirdElephant\Compose\Tweet;

class XController extends Controller { protected $twitter;

public function __construct()
{
    // Initialize the Twitter API client
    $this->twitter = new BirdElephant([
        'bearer_token' => env('TWITTER_BEARER_TOKEN'),
        'consumer_key' => env('TWITTER_CONSUMER_KEY'),
        'consumer_secret' => env('TWITTER_CONSUMER_SECRET'),
        'auth_token' => env('TWITTER_AUTH_TOKEN'), // OAuth 2.0 auth token
    ]);
}

public function post()
{
    $projects = auth()->user()->projects()->get();

    return Inertia::render('Projects/Index', [
        'projects' => $projects,
    ]);
}

// Example method to get followers
public function getFollowers(Request $request)
{
    $username = $request->input('username', 'default_username');
    $followers = $this->twitter->user($username)->followers();
    return response()->json($followers);
}

// Example method to post a tweet
public function tweetSomething(Request $request)
{
    $text = $request->input('text', 'Hello world from Laravel and BirdElephant!');
    $tweet = (new Tweet)->text($text);
    $response = $this->twitter->tweets()->tweet($tweet);
    return response()->json($response);
}

}`

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

you probably need to use oAuth mechanism so that the user can agree to allow you to post on their behalf.

You also need to not use env helper in your code. You should get secrets from a config file and put them into congig files using env helper. In your case most credentials will need to come from the user's authorisation and stored in the user model.

1 like

Please or to participate in this conversation.