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

Abesekara's avatar

Cannot use object of type stdClass as array. How I solve this problem?

This is my function. I need to display it in a productstock.blade.php in a table.

public function notavailable()
	{
		$data = DB::table('products')->where('Qty', '=', 0)->get();
        dd($data);
    }

This is the output of the function.

Illuminate\Support\Collection {#262 ▼
  #items: array:1 [▼
    0 => {#264 ▼
      +"ProductID": 2
      +"Name": "chair"
      +"Brand": "dell"
      +"image": "1616448515.jpg"
      +"Description": "vhvjvkj"
      +"Warranty": "three-year-Warranty"
      +"Price": 7999
      +"Qty": 0
      +"Status": "Active"
      +"AdminID": 1
      +"created_at": "2021-03-22 21:28:35"
      +"updated_at": "2021-03-22 21:34:04"
    }
  ]
}




so. how can I solve this ??

0 likes
8 replies
MichalOravec's avatar
Level 75

You have there a collection of objects

foreach ($data as $item) {
    $item->Name;

    // and so on
}
tykus's avatar

Where are you using the $data variable; somewhere you are iterating over the $data and attempting to array access a property?

Use the object operator instead ,e.g.

@foreach( $data as $product)
	{{ $product->Name }}
@endforeach

Or, use Eloquent models (which are array accessible):

$data = Product::where('Qty', '=', 0)->get();
BRVK's avatar

Everything is perfect in your code.

you should display like, because you are getting data in multi dimentinal array

@foreach($data as $dt)

{{ $dt->ProductId }}

@endforeach

lukasyelle's avatar

It looks like you could be using a Query Scope here, on the Product model, you can define the following:

public function scopeUnavailable($query)
{
	return $query->where('Qty', '=', 0);
}

Then, to use it, you would just do the following:

$unavailableProducts = Product::unavailable()->get()
dd($unavailableProducts);

And in a blade file, assuming you are given the above collection of Products, as other answers have noted, you can utilize Blade's @foreach($unavailableProducts as $product) directive to output the resulting rows with whichever html structure you'd like.

For reference:

https://laravel.com/docs/8.x/eloquent#local-scopes

Please or to participate in this conversation.