我有一个带有可为空字段的数据库。当我通过api resource
发送值时,laravel正在发送null
值。我想改为获取空字符串。如何设置?
例子:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class RequirementResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'active' => $this->active,
'person' => $this->person, //sometimes has null value
'edit' => false,
'buttons' => false,
'text' => $this->text, //sometimes has null value
];
}
}
我想要一个json对象:
{"active": false, "person": "", "edit": false, "buttons": false, "text": ""}
相反,我有:
{"active": false, "person": null, "edit": false, "buttons": false, "text": null}
最佳答案
这里还有一个更大的问题,那就是您的字段一开始是否应该为空。通常,您可以通过使字段不为空来解决此问题,这将迫使您在插入/更新时(而不是在显示时)放入一个空字符串。但是,我的确意识到,在数据库中允许空值,但在返回资源时绝不返回空值并非不合理。
话虽如此,您可以通过以下方式解决您的问题:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class RequirementResource extends Resource
{
public function toArray($request)
{
return [
'active' => $this->active,
'person' => $this->person !== null ? $this->person : '',
'edit' => false,
'buttons' => false,
'text' => $this->text !== null ? $this->text : '',
];
}
}
正如Dvek所提到的,可以将其简化为
$this->text ? : ''
,但需要注意的一点是,对于所有Falset且不一定为null的$this->text ? : ''
值,''
将返回$this->text
。在您的特定情况下,由于text是字符串或null,因此将是相同的,但这并不总是正确的。
关于laravel:如何设置我的资源以提供空字符串而不是null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088688/