Laravel collection converts array to object

人盡茶涼 提交于 2019-11-28 11:31:42

The issue is that the filter() method does not rekey the underlying collection array. So, the Collection is still representing an array, it is just that your array looks like this:

[
    4 => Object4,
    7 => Object7,
]

While this is a perfectly valid array in PHP, this is not a proper array in JSON. Since this cannot be represented as an array in JSON, it is converted to an object in JSON.

In order to get this properly represented as an array in JSON, you just need to rekey the Collection array. The proper method for this is the values() method. All it does is call array_values on the underlying array. This will turn the above array in this:

[
    0 => Object4,
    1 => Object7,
]

Now, this is a proper numerically indexed array that JSON can understand and will treat as an array instead of an object.

While flatten may work for this particular case (your Collection is a collection of Eloquent Models), it is not actually the correct method, and may lead to unintended consequences. Additionally, it will perform a lot of extra logic that is not needed. Your best bet is to use the proper method for what you are trying to achieve, and that is the values() method.

$obj = Cars::with('brand')->orderBy('id')->get();

return $obj->filter(function($value, $key)
    {
        return $value->display == true;
    })
    ->values();

Calling flatten() on your collection should remove the keys and merge all their values up into a single collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!