Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

If you need id as the key, then rely on the Collection:

$collection = Model::all();

$collection->getDictionary();

// returns:
array(
  1 => object(Model) ( ... ),
  2 => object(Model) ( ... ),
  ...
  idN => object(Model) ( ... )
);

Otherwise, nice or not, you can do this:

$keys = $collection->lists('columnName');

$arrayOfModels = array_combine($keys, $collection->getDictionary);
Last updated 2 years ago.
0

I'm not sure the code below was there when this thread was opened, but there's a clean way to do it now:

$collection = Model::all();
$rekeyedCollection = $collection->keyBy('some_attribute');

And in my use case I wanted a unique set of Models so I then used:

$set = $rekeyedCollection = $rekeyedCollection->unique();

Hope that helps :)

0

Sign in to participate in this thread!

Eventy

Your banner here too?

altercode altercode Joined 8 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.