php - Property [id] does not exist on this collection instance in laravel

store a query in array and call the result in view page show Property [id] does not exist on this collection
in controller
foreach($carvalue as $row){
$products[]=DB::table('products')->where('id',$row['product_id'] )->get();
}
and pass the products variable to view page and print the value like
foreach($products as $prod){
if($prod->id==$rows['product_id']){
//code
}
}
show the error and i dd($produts) the result is
array:2 [в–ј
0 => Illuminate\Support\Collection {#491 в–ј
#items: array:1 [в–ј
0 => {#503 в–ј
+"id": "130"
+"title": "Rfdfd"
+"sku": "vbff"
+"sub_title": "RC10 Matte Graphite"
}
]
}
1 => Illuminate\Support\Collection {#505 в–¶}
]
why show this type error and how to solve it ?
Answer
Solution:
In your query, replaceget()
withfirst()
$products[]=DB::table('products')->where('id',$row['product_id'] )->first();
OR
reference the first (and only)$products
as$products[0]
, so it gets theid
from the FIRST (and only, in your case) product
foreach($products[0] as $prod){
if($prod->id==$rows['product_id']){
//code
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key php
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.