Search code examples
laraveltwitteroauth

"Cannot use object of type stdClass as array" error when searching for tweets using the Twitter API


I'm currently working on a project where I'm trying to search for tweets and then save them in a database. For this project I'm using Laravel and TwitterOAuth.

Here's the code:

class TwitterController extends BaseController
{
public function test() {
    $connection = new TwitterOAuth('',
        '',
        '',
        '');
    $content = $connection->get('account/verify_credentials');

    $tweets = $connection->get('search/tweets',
        ['q' => "cryptocurrency"]);

    foreach($tweets as $tweet) {



        $tweet_id = $tweet[0]->id;
        $oembed_j = file_get_contents('https://publish.twitter.com/oembed?url=https://twitter.com/x/status/' . $tweet_id);
        $oembed = json_decode($oembed_j);

        $twitter = new Twitter;
        $twitter->url = $oembed->url;
        $twitter->author_name = $oembed->author_name;
        $twitter->author_url = $oembed->author_url;
        $twitter->html = $oembed->html;
        $twitter->width = $oembed->width;
        $twitter->height = $oembed->height;
        $twitter->type = $oembed->type;
        $twitter->cache_age = $oembed->cache_age;
        $twitter->provider_name = $oembed->provider_name;
        $twitter->provider_url = $oembed->provider_url;
        $twitter->version = $oembed->version;
        $twitter->save();
    }
}

}

and the error:

"(1/1) FatalErrorException
Cannot use object of type stdClass as array

in TwitterController.php (line 27)"

Solution

  • Because $tweets is an object with statuses property you need to iterate over it like this:

    foreach ($tweets->statuses as $tweet)