1

Laravel lists function used to return an array so I could prepend a value. However it now is an object. What I would like to do is generate a list for a dropdown but add an extra value to the front that says something like:

['select a value.', '0']

How should I prepend data to the new Laravel lists function?

Community
  • 1
  • 1
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

2 Answers2

7

lists() returns a Collection object. To add an item to the beginning of the collection, you can use the prepend method:

$statusCollection = \App\Status::lists('name', 'id');
$statusCollection->prepend('select a value', 0);

Make sure you pass in a non-null key as the second parameter to prepend, otherwise this method will end up renumbering your numeric keys. If you don't provide a key, or pass in null, the underlying logic will use array_shift, which will renumber the keys. If you do provide a key, it uses an array union (+), which should preserve the keys.

For another option, you can get the underlying item array using the all() method and just do what you did before:

$statusCollection = \App\Status::lists('name', 'id');
$statusArray = $statusCollection->all();

// if you want to renumber the keys, use array_shift
array_unshift($statusArray, 'select a value');

// if you want to preserve the keys, use an array union
$statusArray = [0 => 'select a value'] + $statusArray;
patricus
  • 59,488
  • 15
  • 143
  • 145
  • lists('name','id')->prepend('Select an option'); is reindexing my collection and i'm losing the original id value. Any suggestions? – zeros-and-ones Apr 27 '16 at 00:02
  • @zeros-ones I have updated my answer. Basically, just make sure you provide a non-null key parameter: `lists('name','id')->prepend('Select an option', 0);` – patricus Apr 27 '16 at 04:22
1

If you are ok with the numeric keys being reindexed, then the accepted answer of using array_unshift() works. If you want to maintain the original numeric keys (for example, if the keys correspond to the id of your table entries), then you could do as follows:

$statusCollection = \App\Status::lists('name', 'id');
$statusArray = $statusCollection->all();
$finalArray = array('0' => 'Select a value') + $statusArray;
Jon
  • 2,277
  • 2
  • 23
  • 33