Preserving Collection Keys in Laravel API Resources

When building APIs, Laravel reindexes resource collections numerically by default. For cases where original keys carry meaning, preserveKeys property maintains the intended data structure.

Preserving Collection Keys in Laravel API Resources

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

Preserving Collection Keys in Laravel API Resources

When building APIs, Laravel reindexes resource collections numerically by default. For cases where original keys carry meaning, preserveKeys property maintains the intended data structure.

 $this->value,
            'updated_at' => $this->updated_at,
            'metadata' => $this->metadata
        ];
    }
}

Here is an example on how this might look in your Laravel applications.

keyBy('key');
        
        return SettingResource::collection($settings);
    }
}

class SettingResource extends JsonResource
{
    public $preserveKeys = true;

    public function toArray($request)
    {
        return [
            'value' => $this->formatValue(),
            'type' => $this->type,
            'last_updated' => $this->updated_at->toDateTimeString(),
            'editable' => $this->is_editable
        ];
    }
}

Then, it would give you a response like this:

{
    "data": {
        "app_name": {
            "value": "My Application",
            "type": "string",
            "last_updated": "2024-03-15 10:30:00",
            "editable": true
        },
        "max_upload_size": {
            "value": 10485760,
            "type": "integer",
            "last_updated": "2024-03-15 10:30:00",
            "editable": true
        }
    }
}

The preserveKeys property ensures meaningful keys are maintained in your API responses, particularly valuable for configuration data and key-value structures.


The post Preserving Collection Keys in Laravel API Resources appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow