I am trying to show orders from a database in Laravel. I have a bit of a problem because it isn't working.
What I want to do:
Show orders per user (on the user profile) with order data, item data, product data, and attribute data.
Here is the ERD I created:
Currently, I made this code, it's not working as it shows 1 order only and the wrong attributes.
$products = Order::where('userid', $userId)->get();
foreach ($products as $product) {
$items = Item::where('order_id', $product->id)->get();
foreach ($items as $item) {
$productname = Product::where('id', $item->product_id)->get();
foreach ($items as $attribute) {
$attribute = Atribute::where('item_id', $attribute->id)->get();
}
}
}
return view('profile', compact('items', 'productname', 'attribute', 'user'));
}
How can I show orders from a user on their profile? What am I doing wrong here?
You were nesting your foreaches a little bit too much.
I removed the foreach here, and just changed $attribute->id
to $item->id
.
foreach ($items as $attribute) {
$attribute = Atribute::where('item_id', $attribute->id)->get();
}
Complete code:
$products = Order::where('userid', $userId)->get();
foreach ($products as $product) {
$items = Item::where('order_id', $product->id)->get();
foreach ($items as $item) {
$productname = Product::where('id', $item->product_id)->get();
$attribute = Atribute::where('item_id', $item->id)->get();
}
}
return view('profile', compact('items', 'productname', 'attribute', 'user'));
You should also have a look at Laravel Relationships to make this whole process easier for you.