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 AppProviders;
use IlluminateHttpResourcesJsonJsonResource;
use IlluminateSupportServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
JsonResource::withoutWrapping();
}
}
Here is an example of how this works when you have withoutWrapping
:
<?php
namespace AppHttpResources;
use IlluminateHttpResourcesJsonJsonResource;
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.
The post Using withoutWrapping to flatten API responses appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.
Source: Read MoreÂ