我正在尝试通过我的Laravel API资源获取返回的region。region是与其他表的关系,所以我通过以下方式访问它:
return [
'region' => ['name' => $this->region->name, 'type' => $this->region->type],
];在region值不为空之前,此操作一直有效。如果region值为空-它会给我一个错误-不能取未定义的名称-所以我试图通过简单地阻止它的发生:
'region' => $this->when($this->region, function(){
return ['name' => $this->region->name, 'type' => $this->region->type];
}),它可以工作,但问题是-当表中的region值为NULL -它没有给出‘region’空数组作为结果-这是我在前端需要的,所以我尝试这样做:
'region' => $this->when($this->region, function(){
return ['name' => $this->region->name, 'type' => $this->region->type];
}),
'region' => $this->when(!$this->region, function(){
return ['name' => '', 'type' => ''];
}),但这是不起作用的-结果中没有空的区域数组:/
我是不是做错了什么,或者是个bug?
发布于 2019-04-10 03:33:17
这比您想象的要简单,您可以对null对象使用可选的helper对象
return [
'region' => [
'name' => optional($this->region)->name,
'type' => optional($this->region)->type
],
];https://stackoverflow.com/questions/51741688
复制相似问题