LaravelのAPIリソースは、デフォルトで「データ」キーに応答をラップします。多くのシナリオには役立ちますが、時にはより平坦な応答構造が必要であり、このようなリソースラップを無効にすることができます。
<!-- Syntax highlighted by torchlight.dev --><?php namespace App\Providers; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { public function boot(): void { JsonResource::withoutWrapping(); } }
:withoutWrapping
<!-- Syntax highlighted by torchlight.dev --><?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class ArticleResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'content' => $this->content, 'author' => new AuthorResource($this->whenLoaded('author')), 'metadata' => [ 'views' => $this->views_count, 'likes' => $this->likes_count, 'published_at' => $this->published_at ] ]; } }
<!-- Syntax highlighted by torchlight.dev -->[ { "id": 1, "title": "Laravel Tips", "content": "Article content here", "author": { "id": 1, "name": "John Doe", "email": "john@example.com" }, "metadata": { "views": 150, "likes": 42, "published_at": "2024-03-15T10:00:00Z" } } ]
リソースラッピングは、APIの応答構造に対する粒状制御を維持しながら、グローバルに無効にすることができます。
以上が並んで使用してAPI応答をフラット化しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。