Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrisblackwell's avatar

Eloquent: Get all items, and set key group

I have a database table called "inventory_items" and each row has a model number and a serial number.

What I'm trying to do is get all the inventory items, but in a group so that I can count all the items of a specific model.

$inventory = InventoryItem::orderBy('model', 'desc')->get();

Is there anyway to set a key for each model?

0 likes
13 replies
pmall's avatar
$inventory = InventoryItem::orderBy('model', 'desc')->get()->groupBy('model');
4 likes
giwrgos's avatar

$inventory = InventoryItem::orderBy('model', 'desc')->groupBy('model')->get();

chrisblackwell's avatar

Hi All

groupBy('model') will not work because that will take out all the entries, and limit each model to a single entry.

giwrgos's avatar

@chrisblackwell what if you create an array of the groups using a loop and then in each group add the items that you want? for example

0 => ["group_name" => "Group A", "data" =>array[0 => "item 1", 1=>"item 2"]]

chrisblackwell's avatar

@giwrgos So far that is what I'm done. Not ideal because I have to run so many queries:


    $inventory = array();

    foreach($models as $model)
    {
      $inventory[$model->model] = InventoryItem::where('model', $model->model)->get();
    }   ```
chrisblackwell's avatar

@pmall You were right! I called it on the collection, not the query, and it worked great :-)

1 like
vincej's avatar

@pmall

Looking at this post, I copied your syntax above:

$contractors = ContractorsController::orderBy('first_name','desc')->get();

and I get and error:

BadMethodCallException in Controller.php line 273: Method [orderBy] does not exist.

I tell you, L5 is flipping confusing between Eloquent, and Query Builder.

I've check the docs and can not see what could be wrong - any ideas??

Many thanks !

vincej's avatar

@bestmomo

It's Friday afternoon in Calgary and I am being an idiot ... sorry to waste your time .. :o)

Bon Soir et Merci !!

pmall's avatar

@vincej

I tell you, L5 is flipping confusing between Eloquent, and Query Builder.

I must say I think it is pretty confusing too that some query builder methods and collection methods are named the same. It is kind of laravel haha moment whent you understand the groupBy method is not the same on a query builder and on a collection.

Please or to participate in this conversation.