Home > Backend Development > PHP Tutorial > Preserving Collection Keys in Laravel API Resources

Preserving Collection Keys in Laravel API Resources

百草
Release: 2025-03-06 02:26:09
Original
864 people have browsed it

Preserving Collection Keys in Laravel API Resources

Laravel renumbers the index of the resource collection by default when building an API. For situations where the original key has meaning, the preserveKeys attribute maintains the expected data structure.

Here is an example of how to use this property in a Laravel application:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class KeyValueResource extends JsonResource
{
    public $preserveKeys = true;

    public function toArray($request)
    {
        return [
            'value' => $this->value,
            'updated_at' => $this->updated_at,
            'metadata' => $this->metadata
        ];
    }
}
Copy after login

Another example:

<?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
        ];
    }
}
Copy after login

This will return 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
        }
    }
}
Copy after login

preserveKeys $preserveKeys = true

The property ensures that meaningful keys are retained in the API response, which is especially important for configuring data and key-value structures. By setting , the Laravel resource collection retains its original key instead of using the default numeric index.

The above is the detailed content of Preserving Collection Keys in Laravel API Resources. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template