The error message "Property [price] does not exist on this collection instance" suggests that the code is trying to access a property on a collection instead of an individual model instance. To fix this, you can use the map method to iterate over the collection and calculate the metadata for each model instance.
Here's an example of how you can modify your code to calculate the metadata:
use App\Http\Resources\CardResource;
Route::apiResource('cards', 'CardController');
class CardController extends Controller
{
public function index()
{
$cards = Card::with('products')->get();
$cardsWithMetadata = $cards->map(function ($card) {
$totalPrice = $card->price * $card->products->sum('price');
return new CardResource($card, $totalPrice);
});
return $cardsWithMetadata;
}
}
In this example, we're using the map method to iterate over the $cards collection and calculate the totalPrice metadata for each model instance. We're then creating a new CardResource instance for each model instance, passing in the model instance and the totalPrice metadata as arguments.
Make sure to update your CardResource class to accept the totalPrice metadata in its constructor and include it in the response.