Reputation: 115
I have 2 tables like this:
+----+-----------+------------+
| id | name | price |
+----+-----------+------------+
| 1 | Product 1 | 20 |
| 2 | Product 2 | 10 |
| 3 | Product 3 | 50 |
| 4 | Product 4 | 40 |
+----+-----------+------------+
+----+-------+------------+---------------------+
| id | price | product_id | created_at |
+----+-------+------------+---------------------+
| 1 | 20 | 1 | 2014-06-21 16:00:00 |
| 2 | 10 | 1 | 2014-06-21 17:00:00 |
| 3 | 50 | 2 | 2014-06-21 18:00:00 |
| 4 | 40 | 2 | 2014-06-21 19:00:00 |
+----+-------+------------+---------------------+
in my index.blade.php I have:
@foreach($products as $product)
@foreach($prices as $price)
<tr>
<td scope="row>">{{$product->id}}</td>
<td >{{$product->name}}</td>
<td>{{$price->price}}</td>
</tr>
@endforeach
@endforeach
but how do I get it that where the {{ $price->price }}
is that i only get the latest price to be shown.
Upvotes: 0
Views: 31
Reputation:
You could modify your code to this
In your Product.php create a relationship
public function prices() {
return $this->hasMany(Price::class);
}
@foreach($products as $product)
<tr>
<td scope="row>">{{$product->id}}</td>
<td >{{$product->name}}</td>
<td>{{$product->prices()->latest()->price}}</td>
</tr>
@endforeach
Upvotes: 1