如何在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
相关产品推荐
相关产品推荐

