Home > Backend Development > PHP Tutorial > Dynamic API Response Control in Laravel Resources

Dynamic API Response Control in Laravel Resources

Emily Anne Brown
Release: 2025-03-06 01:42:13
Original
137 people have browsed it

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 loaded
  • whenNotNull(): The attribute is included only if the attribute is not null
  • : Contains attributes only if they exist on the model whenHas()
The following is an example of using conditional properties:

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),
        ];
    }
}
Copy after login
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()
            ),
        ];
    }
}
Copy after login
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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template