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