MrCujo
MrCujo

Reputation: 1323

Laravel: cannot access item from a collection

I've got some data returned as a collection from a relationship:

$item = $this->detailedItems->where('detaileditem_product_id', $productId);

when printing this out I can see the data I'm looking for but when trying to access it:

$item->detaileditem_id;

or

$item->detaileditem_name;

I'm getting an error:

Exception: Property [detaileditem_id] does not exist on this collection instance.

Upvotes: 0

Views: 140

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

where returns a filtered collection, not a single item.

If you want the first item of that collection that matches your condition, use first:

$item = $this->detailedItems->where('detaileditem_product_id', $productId)->first();

Upvotes: 1

Related Questions