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响应结构的颗粒状控制,从而更加直观,更易于处理端点。
>
以上是使用不包装来平坦的API响应的详细内容。更多信息请关注PHP中文网其他相关文章!