首页 > 后端开发 > php教程 > 保留Laravel API资源中的收集键

保留Laravel API资源中的收集键

百草
发布: 2025-03-06 02:26:09
原创
862 人浏览过

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板