You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel whenLoaded资源中获取单个字段?

Laravel Resource 可选关联仅返回指定字段的解决方案

方法一:利用whenLoaded的闭包回调(推荐)

whenLoaded支持传入闭包作为第二个参数,仅在关联加载时执行闭包逻辑,安全返回指定字段:

public function toArray(Request $request): array
{
    return [
        'id'                 => (string) $this->id,
        'attributes'         => [
            'name'             => $this->name,
            'status_id'        => $this->status_id,
            'created_at'       => $this->created_at,
            'updated_at'       => $this->updated_at,
        ],
        'relationships' => [
            'status' => $this->whenLoaded('status', function () {
                return $this->status->name;
            }),
        ]
    ];
}

当status关联未加载时,该字段会自动从响应中剔除,不会触发报错。

方法二:结合optional辅助函数

如果需要保留status字段键(关联未加载时返回null),可以用optional处理:

'relationships' => [
    'status' => optional($this->whenLoaded('status'))->name,
]

方法三:手动判断关联状态

通过relationLoaded方法直接判断关联是否加载,再返回对应值:

'relationships' => [
    'status' => $this->relationLoaded('status') ? $this->status->name : null,
]

内容的提问来源于stack exchange,提问作者BobbyP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 18:04:58