在構建 API 時,Laravel 默認情況下會將資源集合的索引重新編號為數字。對於原始鍵具有意義的情況,preserveKeys
屬性可保持預期的數據結構。
以下是如何在 Laravel 應用程序中使用此屬性的示例:
<?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 ]; } }
另一個例子:
<?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 ]; } }
這將返回類似這樣的響應:
{ "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
屬性確保在 API 響應中保留有意義的鍵,這對於配置數據和鍵值結構尤其重要。 通過設置 $preserveKeys = true
,Laravel 資源集合將保留其原始鍵,而不是使用默認的數字索引。
以上是保留Laravel API資源中的收集鍵的詳細內容。更多資訊請關注PHP中文網其他相關文章!