I am playing for the first time with API Resource in laravel 12.
I have this situation:
The product has many Skus:
public function skus(): HasMany
{
return $this->hasMany(Sku::class);
}
The skus has many images:
public function images(): HasMany
{
return $this->hasMany(SkuImage::class)->orderBy('sort');
}
So from the product controller I use:
Product::with(['skus.images'])....
to receive the skus and the images.
In ProductResource:
...
'skus' => $this->whenLoaded('skus', function () {
return $this->skus->map(function ($sku) {
return [
'id' => $sku->id,
...
// the problem is here -> Call to undefined method App\\Models\\Sku::whenLoaded()
'images' => $sku->whenLoaded('images', function ($sku) {
return $sku->images->map(function ($image) {
return [
'id' => $image->id,
'filename' => $image->filename,
'size' => $image->size,
];
});
}),
];
});
}),
...
I want to load the images only when the images relation is loaded from skus with(['skus.images']), else show only the sku data with(['skus']) when not loading the images.
How can I do that?