Home » Php » php – Call to undefined method stdClass::count() in laravel

php – Call to undefined method stdClass::count() in laravel

Posted by: admin February 25, 2020 Leave a comment

Questions:

I trying to paginate my JSON response but got error like this

Call to undefined method stdClass::count()

My JSON response from the Laravel API by using guzzle ……

here is my controller code

public function index()
{
    $response =  $this->client->get('getUserIndex')->getBody();
    $content = json_decode($response->getContents());
    $total = $content->count();
    $paginationRecord = CollectionPaginate::paginate($content, $total, '15');
    return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord->data]);
}
How to&Answers:
$content = json_decode($response->getContents());
$total = $content->count();

I am not entirely sure why you think the result of json_decode would have a count method? The JSON decoding always results in a generic object (stdClass) since there’s no way for the PHP interpreter to know it represents an available class.

The ->count method is available on Countable implementations (such as ArrayCollection). If you expect a Countable class, then you can either have a factory to build your object from JSON or try to cast the stdClass to ArrayCollection.

Otherwise, if your JSON data is a valid array, you can try to use

$decoded = json_decode($data, true)

meaning it will decode it to an array rather than an object, which enables you to do

count($decoded)

Answer:

$content is an object, not a collection or array you can use php method count with array get $total

Please Change to

 public function index()
        {


            $response =  $this->client->get('getUserIndex')->getBody();
            $content = json_decode($response->getContents(),true );
            $total = count($content);
            $paginationRecord = CollectionPaginate::paginate($content, $total, '15');
            return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord->data]);

}