I am new in Laravel. I have two table 1- Product 2- Product_Price. I want to show the last product Price in Product Page but I tried different methods but getting errors.
My controller code:
public function show(Request $request, Product $product): View
{
$this->authorize('view', $product);
$ProductTags = $product->ProductTags;
$ProductPrice = $product->ProductPrices->last();
return view('app.products.show', compact('product', 'ProductTags', 'ProductPrice'));
}
My blade code is:
@foreach ($ProductPrice as $productprice)
<div>
{{ $productprice->price }}
</div>
@endforeach
But I am getting this error:
Attempt to read property "price" on bool
$ProductPrice = $product->ProductPrices->last();
This gives you a single object, not a collection. You don't need to loop over in the view to get object values.
<div>
{{ $ProductPrice->price }}
</div>
This will give the expected output.
When you loop over an object, the value of the loop variable is boolean. Hence you are getting the error.