在构建 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中文网其他相关文章!