I have a nested collection that I want to transform, pulling some keys "up a level" and discarding some other keys.
Every item in the collection has an allergens property.
"allergens": [
        {
            "id": 2001,
            "info": "Allergy advice",
            "status": "does_contain",
            "product_id": 71576,
            "allergen_id": 1,
            "allergen": {
                "id": 1,
                "name": "Celery"
            }
        },
        {
            "id": 2002,
            "info": "Allergy advice",
            "status": "may_contain",
            "product_id": 71576,
            "allergen_id": 11,
            "allergen": {
                "id": 11,
                "name": "Peanuts"
            }
        }
    ],
I need to make each items allergens property, look like
"allergens": [
        {
            "id": 1,
            "name": "Celery"
            "status": "does_contain",
        },
        {
            "id": 11,
            "name": "Peanuts"
            "status": "does_contain",
        },
    ],
I've tried.
$collection = $collection->transform(function ($item, $key) {
    $item->allergens = $item->allergens->map(function ($allergen) {
        return [
            'id' => $allergen->allergen->id,
            'name' => $allergen->allergen->name,
            'status' => $allergen->status,
        ];
    });
    
    return $item;
});
But it doesn't overwrite the allergens property
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire