Using withoutWrapping to flatten API responses
Last updated on by Harris Raftopoulos
Laravel's API resources wrap responses in a 'data' key by default. While useful for many scenarios, sometimes a flatter response structure is needed and you can disable resource wrapping like this:
<?php namespace App\Providers; use Illuminate\Http\Resources\Json\JsonResource;use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider{ public function boot(): void { JsonResource::withoutWrapping(); }}
Here is an example of how this works when you have withoutWrapping
:
<?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 ] ]; }}
Example response with wrapping disabled:
[ { "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" } }]
This implementation provides a cleaner API structure while maintaining the flexibility to customize response formats based on your application's needs.
Resource wrapping can be disabled globally while still maintaining granular control over your API's response structure, resulting in more intuitive and easier-to-consume endpoints.