Home >Backend Development >PHP Tutorial >Dynamic API Response Control in Laravel Resources
Laravel API resources provide an elegant way to conditionally include properties in responses, allowing you to create flexible and efficient APIs to suit different contexts and permissions.
When building APIs, you often need to customize your responses based on different scenarios—for example, only display certain fields to administrators, only include relevant data when requested, or adjust the response format based on endpoints. Laravel's API resources provide a powerful way to handle these situations through conditional properties.
Some key methods available are:
when()
: The attribute is included only if the condition is true whenLoaded()
: Contains relationship only if it has been loadedwhenNotNull()
: The attribute is included only if the attribute is not 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), ]; } }Let's explore a practical example of a catalog API with conditional data:
<?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() ), ]; } }The conditional properties in the Laravel API resource enable you to build context-aware responses while keeping your code simple and easy to maintain.
The above is the detailed content of Dynamic API Response Control in Laravel Resources. For more information, please follow other related articles on the PHP Chinese website!