0

I build a Laravel API using resources. It return a collection plus some extra meta data. I want to remove the null item(s) without losing my formatted JSON response. Note: I tried filter method but it removed "data" and "extra_meta" from the JSON response. In other word it altered the collection heavily and it didn't just removed null item(s).

{
    "data": [
        {
            "data_1": "some data"
        },
        {
            "data_1": "some data"
        },
        null,
        null,
        null,
        null,
        null,
        null
    ],
    "extra_meta": {
        "meta_1": "some meta"
    }
}

Here is a simplified code using resource

       return $collection = someResource::collection($somthing)->additional([
            'extra_meta' => [
                'meta_1' => $request->metaInfo,
            ],
        ]);
Mano
  • 55
  • 7
  • 3
    Rather than trying to remove them, why don't you look at stopping them from being in the collection in the first place. Why are `null` values coming through? – James Sep 02 '19 at 00:04

1 Answers1

0

@Mano.

In php docs we have a function called array_filter(), if you use it like this:

echo (array_filter($data, function($value) { return !is_null($value) && $value !== ''; }))

The function array_filter() when its used with no callback (the second parameter) remove all null keys in array, but you can customize the function apllying a callback like the code above where i put a function that return only things that is not null and different than ''.

Hope i helped you.

EDIT: i recommend you to put the data array in a separated variable

$data = <json response>['data'];

after this use the function,

see the PHP docs here https://www.php.net/manual/en/function.array-filter.php

  • Collection is an object not array and I cant use your recommendation to create a separate array 'data' then filter it then rejoin it with the 'extra_meta' since this will make the response extremely slow. I rather stick to the null value over your recommendation – Mano Sep 02 '19 at 02:10