首頁 > 後端開發 > php教程 > 保留Laravel API資源中的收集鍵

保留Laravel API資源中的收集鍵

百草
發布: 2025-03-06 02:26:09
原創
865 人瀏覽過

Preserving Collection Keys in Laravel API Resources

在構建 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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板