最佳答案
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 :)