Search code examples
laravelserializationlaravel-collection

Laravel Collection Filter breaking serialization format


I have a serialized String like this

$string = '[{"name":"FOO"},{"name":""},{"name":"BAR"}]';

I am trying to process it via Laravel Collection's filter method and eliminate items without a defined "name" property.

$collection = collect(\json_decode($string));
$collection = $collection->filter(function($v){
    return !empty($v->name);
});
$string = \json_encode($collection->toArray());
dd($string);

Normally I am expecting something like this:

[{"name":"FOO"},{"name":"BAR"}]

But I'm getting something like this:

{"0":{"name":"FOO"},"2":{"name":"BAR"}}

Funny thing is, if I skip the filtering process or return true every time, I keep getting the string in the desired format. Removing the toArray() call has the same result. I don't want to keep the numeric indices as associative object keys.

Why this anomaly? And what should I do to get the serialized data in desired format?


Solution

  • In PHP arrays the index key must be unique. In your case you have the key 'name' and collection automatically assigns the index key to all items in the collection.

    To overcome that problem just call

    $string = \json_encode($collection->values());