ホームページ >バックエンド開発 >PHPチュートリアル >Laravel APIリソースの保存コレクションキー
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 サイトの他の関連記事を参照してください。