Laravel Tutorials

Preserving Collection Keys in Laravel API Resources

Published
Preserving Collection Keys in Laravel API Resources image

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

<?php
	
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class KeyValueResource extends JsonResource
{
    public $preserveKeys = true; // [tl! focus]
	
    public function toArray($request)
    {
        return [
            'value' => $this->value,
            'updated_at' => $this->updated_at,
            'metadata' => $this->metadata
        ];
    }
}

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

<?php
	
namespace App\Http\Controllers;

use App\Models\Setting;
use App\Http\Resources\SettingResource;

class SettingController extends Controller
{
    public function index()
    {
        $settings = Setting::all()->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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article
PIE 1.5 Changes PHP Extension Installs in CI image

PIE 1.5 Changes PHP Extension Installs in CI

Read article
Delete Expired Sessions in Laravel With a Scheduled Command image

Delete Expired Sessions in Laravel With a Scheduled Command

Read article
Pollora: Run WordPress Inside a Laravel Application image

Pollora: Run WordPress Inside a Laravel Application

Read article
Scheduled Session Garbage Collection in Laravel 13.39 image

Scheduled Session Garbage Collection in Laravel 13.39

Read article