Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

movepixels's avatar

Return an Empty Resource

I am working on implementing the Laravel API Resource to an existing site. One problem I find is that if there are no records the JSON response is null, yet the recource its-self has other coded features like link / meta data.

Controller:

AvailabilityResource::withoutWrapping();
return new AvailabilityResource($profile->availability); // single record hasOne relationship so will never be a collection of records

AvailabilityResource:

public function toArray($request)
{
  $profile = \Route::current()->parameter('profile');

  return [
    'type' => 'availability',
    'attributes' => [
      'expires_at' => $this->expires_at,
      'expires' => $this->expires
    ],
    'meta' => [
      'store' => 'availabilityStore'
    ],
    'links' => [
      'index' => [
          'url' => route('availability.index', ['profile' => $profile]),
          'method' => 'get',
        ],
      'update' => [
        'url' => route('availability.create', ['profile' => $profile]),
        'method' => 'post',
      ]
    ],
  ];
}

But this returns availability: null as a response. No other required data?

Am I missing something?

Thanks,

Dave

0 likes
2 replies
jlrdw's avatar

json_decode it first then check if empty.

movepixels's avatar

No clue why do that. The whole point of the API Resource is to return a JSON object. This dashboard request has hundreds objects to build the dashboard so to me its somes odd to json_decod each then check if it has something?

Either way I solved it using the Resource and Collection as needed / documented so no worries.

Thanks all the same for your insight.

Please or to participate in this conversation.