I've got a database with nullable fields. When I send my values via api resource
, laravel is sending null
values. I want to get empty strings instead. How can I set it up?
example:
<?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
];
}
}
I want a json object:
{"active": false, "person": "", "edit": false, "buttons": false, "text": ""}
instead I've got:
{"active": false, "person": null, "edit": false, "buttons": false, "text": null}
There's a greater question that comes into play here and it's whether your field should be nullable to begin with. Normally you could solve this by not having the field to be nullable which will force you to put an empty string in at insert/update time instead of when displaying it. However I do realise that it's not unreasonable to allow nulls in the database but never return them when returning the resource.
This being said you can solve your problem as follows:
<?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 : '',
];
}
}
As Dvek mentioned this can be shortened to $this->text ? : ''
but there's a small caveat that $this->text ? : ''
will return ''
for all values of $this->text
which are falsey and not necessarily null. In your particular case since text is either a string or null it will be the same but this is not always true.