'PHP Error: Cannot use object of type stdClass as array in Laravel

Using Laravel 6 Getting error

Cannot use object of type stdClass as array

I converted my query to an array.

$filterQuery = DB::table('view_vi_properties');
$filterQuery->select('id','name','bedrooms','max_guests','min_stay','private_pool','private_pool_text','price','security_deposit','pets_allowed','latitude','longitude','pro_address1','pro_address2','pro_city','country','primary_image','slug','rooms');
$filterQuery->whereNotIn('id', explode(',', $comma_property_id));
$filterQuery->whereNotIn('rooms_id', explode(',', $comma_room_id));
$filterQuery->whereNotIn('block_name', explode(',', $comma_block_name));
$filterQuery->where('status', 1)->groupBy('id');
$filterQuery->orderBy('name', 'asc');
$results = $filterQuery->get()->toArray();
print_r($results);

and I'm getting an array but the error is still showing

Array   (
    [0] => stdClass Object
        (
            [id] => 4
            [name] => Candolim
            [bedrooms] => 5
            [max_guests] => 9
            [min_stay] => 3
            [primary_image] => 1646566320.jpg
            [slug] => candolim
            [rooms] => 7 BR
        )
   )


Solution 1:[1]

$filterQuery->get() returns you a Collection of StdClass items, and toArray() converts only Collection object, but not items inside of it (not working recursively as you want).

The easiest way is to change DB::table('view_vi_properties'); to corresponding Eloquent model, lets assume you model is ViewViProperties.In this case $filterQuery->get() will return a Collection of ViewViProperties class and toArray() will be able to convert all data to array recursivley.

If you don't want to use Eloquent then you need to convert each item separately or refer to them with object syntax like $results[0]->id.

Solution 2:[2]

The issue mentioned above is correct because toArray() converted the parent objects to an array, but not child objects. To convert child objects to array also can be achieved through:

$result  = json_decode(json_encode($results), true);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sona Khachatryan
Solution 2 Ali Zaib