Home > Mobile >  Returning empty object in Laravel resource instead of null
Returning empty object in Laravel resource instead of null

Time:01-06

I do have a resource (DeviceResource) in my Laravel API which contains another resource (SimcardResource). There is a OnetoOne relationship between those resources but sometimes a device has no associated simcard. If this is the case my DeviceResource returns for the simcard null instead of an empty json object. I do need an empty json object because I present information called from my API in my Vue frontend by accessing an object e.g. like device.simcard.phone_number

My DeviceResource class looks like this:

    public function toArray($request)
    {
        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'))  ?: (object)[],
        ];
    }

The commented section:

'simcard' => $this->resource->simcard ?: (object)[]

Works perfectly but returns all fields from my simcard table but I only need fields defined in my SimcardResource class so I tried the following:

'simcard' => SimcardResource::make($this->whenLoaded('simcard'))  ?: (object)[]

But it still returns null instead of an empty json object.

CodePudding user response:

Laravel introduce best ways,for example whenLoaded,but try this

... ?? json_encode(new stdClass)

CodePudding user response:

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.

  • Related