如何在没有重建索引的情况下将项目添加到laravel列表集合中?

时间:2016-04-27 00:11:02

标签: php laravel oop collections

尝试将collectino传递给视图中的表单选择。 prepend方法正在重新索引集合,并且我失去了正确的公司ID。

$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"
 * ]
 */

我现在在prepend方法中查找Collection对象,这里是:

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

    return $this;
}

1 个答案:

答案 0 :(得分:4)

好的,我很快找到了解决方案。通过传递第二个参数的键,我使用0,该方法将保持原始键。

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

 \*
  * {
  *     "0": "Select a company",
  *     "3": "Test 123 ",
  *     "4": "wer"
  * }
  *\
相关问题