0

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?

Edward Ellsworth
  • 455
  • 5
  • 12
  • What happens if you do `dd($skills);` ? – harshpatel991 Nov 21 '17 at 04:05
  • 1
    The results are the same, it's just the keys in the collection are different. The `where()` method does not rekey the collection. Because your framework collection is not a proper json array (must be numerically indexed, in order, starting at 0), it must be represented as an object. Call `values()` on your collection to rekey it, and then it can be represented as a json array. Easier to read explanation is in duplicate flagged answer. – patricus Nov 21 '17 at 05:47

0 Answers0