Filtering Eloquent collection data with $collection->filter()

The collection’s filter method calls array_filter on the underlying array, which, according to the PHP docs, preserves the array keys. This then results in your array being converted to a JavaScript object instead of an array.

Call values() on your collection to reset the keys on the underlying array:

$filtered_collection = $collection->filter(function ($item) {
    return $item->isDog();
})->values();

Side note: in newer versions of Laravel, you can use a higher order message to shorten the above into this:

$filtered_collection = $collection->filter->isDog()->values();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)