首頁 >後端開發 >php教程 >使用不包裝來平坦的API響應

使用不包裝來平坦的API響應

Robert Michael Kim
Robert Michael Kim原創
2025-03-06 02:47:14856瀏覽

Using withoutWrapping to flatten API responses

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 [
            &#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
            ]
        ];
    }
}
禁用包裝的示例響應:

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:laravel的深陣列操縱下一篇:暫無