首頁 >後端開發 >php教程 >Laravel資源中的動態API響應控制

Laravel資源中的動態API響應控制

Emily Anne Brown
Emily Anne Brown原創
2025-03-06 01:42:13137瀏覽

Dynamic API Response Control in Laravel Resources

Laravel API 資源提供優雅的方法來有條件地包含響應中的屬性,允許您創建靈活高效的 API,以適應不同的上下文和權限。

在構建 API 時,您經常需要根據不同的場景自定義響應——例如,僅向管理員顯示某些字段,僅在請求時包含相關數據,或根據端點調整響應格式。 Laravel 的 API 資源通過條件屬性提供強大的方法來處理這些情況。

一些可用的關鍵方法是:

  • when():僅當條件為真時才包含屬性
  • whenLoaded():僅當關係已加載時才包含關係
  • whenNotNull():僅當屬性不為 null 時才包含屬性
  • whenHas():僅當模型上存在屬性時才包含屬性

以下是一個使用條件屬性的示例:

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

class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->when($request->user()->isAdmin(), $this->email),
        ];
    }
}

讓我們探索一個具有條件數據的產品目錄 API 的實際示例:

<?php namespace App\Http\Resources;

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

class ProductResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'price' => $this->price,

            // 仅在详细视图中包含完整描述
            'description' => $this->when(
                $request->route()->named('products.show'),
                $this->description,
                $this->excerpt
            ),

            // 为已认证的用户包含库存信息
            'stock_level' => $this->when(
                $request->user()?->can('view-inventory'),
                $this->stock_count
            ),

            // 加载时包含关系
            'category' => new CategoryResource($this->whenLoaded('category')),

            // 有条件地包含计数
            'reviews_count' => $this->when(
                $request->include_counts,
                $this->reviews_count
            ),

            // 包含管理员数据
            'profit_margin' => $this->when(
                $request->user()?->isAdmin(),
                fn() => $this->calculateProfitMargin()
            ),
        ];
    }
}

Laravel API 資源中的條件屬性使您能夠構建上下文感知的響應,同時保持代碼簡潔易維護。

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

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