Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend item to laravel lists collection without reindexing?

Trying to pass a collectino to a form select in the view. The prepend method is re-indexing the collection and I'm losing the correct company ids.

$companies = Company::lists('name','id');
return $companies;

/*
 * {
 *     "3": "Test 123 ",
 *     "4": "wer"
 *  }
 */

$companies->prepend('Select a company');
return $companies;

/*
 * [
 *      "Select a company",
 *      "Test 123 ",
 *      "wer"
 * ]
 */

I'm looking in the Collection object at the prepend method now, here it is:

public function prepend($value, $key = null)
{
    $this->items = Arr::prepend($this->items, $value, $key);

    return $this;
}
like image 651
zeros-and-ones Avatar asked Apr 27 '16 00:04

zeros-and-ones


1 Answers

Ok I quickly found a solution. By passing a key for the second argument, I'm using 0, the method will maintain the original keys.

$companies->prepend('Select a company', 0);
return $companies;

 \*
  * {
  *     "0": "Select a company",
  *     "3": "Test 123 ",
  *     "4": "wer"
  * }
  *\
like image 159
zeros-and-ones Avatar answered Oct 11 '22 03:10

zeros-and-ones