I'm trying to filter the following collection using the collection filter() method:
$collection = Word::all();
where the JSON output looks like this:
[ { "id": "1", "word": "dog", "phonetic": "dog", "mean": "pies", "assoc": "some example text", "author_id": "3", "user_id": "3" }, { "id": "2", "word": "sun", "phonetic": "sun", "mean": "słońce", "assoc": "lorem ipsun dolor sit amet", "author_id": "3", "user_id": "2" }, ... ]
However, when filtering the collection:
$filtered_collection = $collection->filter(function($item) { if($item->isDog()) { return $item; } });
The filtered collection JSON output will look like this:
{"1": { "id": "1", "word": "dog", "phonetic": "dog", "mean": "pies", "assoc": "some example text", "author_id": "3", "user_id": "3" }, "2": { "id": "2", "word": "sun", "phonetic": "sun", "mean": "słońce", "assoc": "lorem ipsun dolor sit amet", "author_id": "3", "user_id": "2" }}
How can I keep the original JSON output when filtering a collection? I'd like to have an array of my Eloquent model instances when filtering the original collection . Thanks in advance :)
You can filter Java Collections like List, Set or Map in Java 8 by using the filter() method of the Stream class. You first need to obtain a stream from Collection by calling stream() method and then you can use the filter() method, which takes a Predicate as the only argument.
$filteredArray = Arr::where($myArray, function ($value, $key) { return $value['type'] == 1; }); This is how you can use Arr::where in your array, and should work fine. Also for things like this laravel collections have really handy tools, you should have a look at it as well.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With