ホームページ >バックエンド開発 >PHPチュートリアル >Laravel APIリソースの保存コレクションキー

Laravel APIリソースの保存コレクションキー

百草
百草オリジナル
2025-03-06 02:26:09862ブラウズ

Preserving Collection Keys in Laravel API Resources

laravelは、APIを構築するときにデフォルトでリソースコレクションのインデックスを削除します。元のキーに意味がある状況では、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

以上がLaravel APIリソースの保存コレクションキーの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。