首頁 > 後端開發 > php教程 > Laravel API中的資源響應自定義

Laravel API中的資源響應自定義

Robert Michael Kim
發布: 2025-03-05 15:22:14
原創
452 人瀏覽過

Resource Response Customization in Laravel APIs

Laravel's

方法提供了增強API響應的強大方法。 它使您可以在發送給客戶端之前修改HTTP響應對象,超越簡單的數據調整,以包含標頭,狀態代碼和其他響應屬性。 withResponse>

這對於構建需要傳達元數據,版本詳細信息或自定義標題的強大API特別有用。

>

這是一個基本示例:

class UserResource extends JsonResource
{
    public function withResponse($request, $response)
    {
        $response->header('X-Resource-Type', 'User');
    }
}
登入後複製
此示例演示了更全面的API響應自定義:>

>通過利用
<?php namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Request;

class DocumentResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->when(
                $request->user()->canViewContent($this->resource),
                $this->content
            ),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at
        ];
    }

    public function withResponse(Request $request, $response)
    {
        $response->header('X-Document-ID', $this->id);

        if ($this->is_public) {
            $response->header('Cache-Control', 'public, max-age=3600');
            $response->header('ETag', md5($this->updated_at));
        }

        if ($this->wasRecentlyCreated) {
            $response->setStatusCode(201);
        }

        if ($request->has('include_legacy')) {
            $response->header('X-Deprecated-Fields', 'legacy_format,old_structure');
            $response->header('X-Deprecation-Date', '2024-07-01');
        }
    }
}
登入後複製
方法,您的API資源從單純的數據持有器演變為完全可自定義的HTTP響應,並在核心數據旁邊用必需的元數據豐富您的API。

以上是Laravel API中的資源響應自定義的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板