I wrote a relation belongsToMany between products and photos and now I want to show products in the home page. I did it like so:
@foreach ($latestProducts as $product)
<img src="{{$product->photos()->path}}">
@endforeach
homeController:
public function index()
{
$latestProducts = Product::orderBy('created_at' , 'desc')->limit(10)->get();
return view('front.layouts.index' , compact('latestProducts'));
}
photo model:
public function products() {
return $this->belongsToMany(Product::class);
}
product model:
public function photos() {
return $this->belongsToMany(Photo::class);
}
I got Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$path .And when I write {{$product->photos[0]->path}} , the error changes to "Undefined array key 0. Also when I write {{$product->photos->path}} ,I get an error as "Property [path] does not exist on this collection instance."
CodePudding user response:
I believe you got a photo
attribute/field in the Photo
model. Because photos
is a collection of photos, you might want to write:
@foreach ($latestProducts as $product)
@foreach ($product->photos as $photo)
<img src="{{$photo->path}}">
@endforeach
@endforeach
And only the first photo:
@foreach ($latestProducts as $product)
<img src="{{$product->photos->first()->path}}">
@endforeach
// Or to be safe
@foreach ($latestProducts as $product)
<img src="{{optional($product->photos->first())->path}}">
@endforeach
// Or this in php 8
@foreach ($latestProducts as $product)
<img src="{{$product->photos->first()?->path}}">
@endforeach
CodePudding user response:
You have to use
{{ $product->photos->path }}
cause when you deal with relations in blade you deal with it as a property of class of the father class unlike when you deal with it in eloquent ORM you can use photos()
CodePudding user response:
Basically the error is saying that there is no property photos in the $products. Assuming that the table name is correct and the foreign keys too
you can just do:
public function index()
{
$latestProducts = Product::with('photos')->orderBy('created_at' , 'desc')->limit(10)->get();
return view('front.layouts.index' , compact('latestProducts'));
}
And in blade file try to remove the (), because it will load the relationship.
@foreach ($latestProducts->photos as $product)
<img src="{{$product->path}}">
@endforeach