I have a skills table with a category column. I want to get all the results from the table, loop through the categories and filter the results from the table by each category.
To do this I figured I would use Laravel's collection where method. The trouble is, I'm not getting consistent results.
I wrote this to compare the different outputs:
$skills = Skill::all();
$frameworks = $skills->where('category', 'Frameworks');
$backend = $skills->where('category', 'Backend');
return [
'db_backend' => Skill::where('category', 'Backend')->get(),
'collection_backend' => $backend,
'db_frameworks' => Skill::where('category', 'Frameworks')->get(),
'collection_frameworks' => $frameworks
];
This gives me the following output:
{
"db_backend": [
{
"id": 1,
"created_at": "2017-11-20 02:39:20",
"updated_at": "2017-11-20 02:39:20",
"name": "PHP",
"notes": "",
"category": "Backend"
}
],
"collection_backend": [
{
"id": 1,
"created_at": "2017-11-20 02:39:20",
"updated_at": "2017-11-20 02:39:20",
"name": "PHP",
"notes": "",
"category": "Backend"
}
],
"db_frameworks": [
{
"id": 2,
"created_at": "2017-11-20 02:39:20",
"updated_at": "2017-11-20 02:39:20",
"name": "Wordpress",
"notes": "",
"category": "Frameworks"
}
],
"collection_frameworks": {
"1": {
"id": 2,
"created_at": "2017-11-20 02:39:20",
"updated_at": "2017-11-20 02:39:20",
"name": "Wordpress",
"notes": "",
"category": "Frameworks"
}
}
}
So, the where method as an Eloquent query gives consistent output. But the where method for the collection seems to be adding an extra key, but not in both cases. The only thing I can see that is different about the "PHP" skill is that it was the first entry into that table, but I don't see why that would cause this behavior.
Am I doing something wrong or is this a bug?