0👍
✅
It is Laravel resource default behaviour that if you do not have any data than resource will also return you the null resource object. You have to manage it yourself in other way like by defining each parameter has null value that’s it.
1👍
Okay maybe its not the best solution but my DeviceResource class now looks like this:
public function toArray($request)
{
if (is_null($this->resource->simcard)) {
return [
'id' => $this->resource->id,
'model' => $this->resource->model,
'device_name' => $this->resource->device_name,
'operating_system' => $this->resource->operating_system,
'os_version' => $this->resource->os_version,
'emei' => $this->resource->emei,
'device_password' => $this->resource->device_password,
'purchase_date' => $this->resource->purchase_date,
'associated_worker' => $this->resource->associated_worker,
'remarks' => $this->resource->remarks,
'device_status_id' => $this->resource->device_status_id,
'simcard' => (object) [],
];
} else {
return [
'id' => $this->resource->id,
'model' => $this->resource->model,
'device_name' => $this->resource->device_name,
'operating_system' => $this->resource->operating_system,
'os_version' => $this->resource->os_version,
'emei' => $this->resource->emei,
'device_password' => $this->resource->device_password,
'purchase_date' => $this->resource->purchase_date,
'associated_worker' => $this->resource->associated_worker,
'remarks' => $this->resource->remarks,
'device_status_id' => $this->resource->device_status_id,
// 'simcard' => $this->resource->simcard ?: (object)[],
'simcard' => SimcardResource::make($this->whenLoaded('simcard')),
];
}
}
0👍
Laravel introduce best ways,for example whenLoaded,but try this
... ?? json_encode(new stdClass)
Source:stackexchange.com