Skip to content

Instantly share code, notes, and snippets.

@aquasmit
Created December 19, 2016 03:41
Show Gist options
  • Save aquasmit/138b4e4bae14b0637f9ac055c76b7c4e to your computer and use it in GitHub Desktop.
Save aquasmit/138b4e4bae14b0637f9ac055c76b7c4e to your computer and use it in GitHub Desktop.
Laravel - collection's keyBy function() to arrange records by one the keys

I found the solution with the function keyBy() on the collection (using laravel 5.1, 5.2)

 $collection = $collection->keyBy('id');

If you want to forget an item of your collection it unsets the right one then use following.

$collection->forget($item->id);
@AleksandarSavic95
Copy link

Thanks! :) Good to know is that you can pass a function as a parameter to keyBy to determine the key value:

items()->get()->keyBy(function ($item) {
    return $item->field->whatever; // index the collection by a specific sub-field value
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment