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}
$this->text !== null ? $this->text : ''
? (same for person) – Setscrew$this->text ?: ''
– Acrocarpous