sahar_mkr's avatar

api resource

hi everyone, I have many to many relationship, now I want to show all models with all the relations, and use a metadata just to multiply two attributes of the two relations, I have cart and product model, these models have many to many relationships, and I want to show card with products, so I used: Card::with('products'); and then I used apiResource to show them with metadata that multiples one attribute of card with one attribute of the product, I used the way below, but It says Property [price] does not exist on this collection instance, How can I get that?

0 likes
1 reply
LaryAI's avatar
Level 58

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.

Please or to participate in this conversation.