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 ]; } }
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 ]; } }
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 } } }
preserveKeys
$preserveKeys = true
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!