Home >Backend Development >PHP Tutorial >Using withoutWrapping to flatten API responses

Using withoutWrapping to flatten API responses

Robert Michael Kim
Robert Michael KimOriginal
2025-03-06 02:47:14849browse

Using withoutWrapping to flatten API responses

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.

<!-- 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();
    }
}

Here is an example of how this works when you have 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 [
            &#39;id&#39; => $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:

<!-- 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"
        }
    }
]

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 above is the detailed content of Using withoutWrapping to flatten API responses. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn