How to add an Laravel Eloquent Collection array with a key-value pair?

I am extracting something from the database:

$foo = $this->fooRepository->all()->lists('name', 'id');

I get:

Collection {#506 ▼
  #items: array:9 [▼
    "9c436867-afe9-4234-a849-253aea4f602c" => "aaa"
    "d250102b-1370-40d0-99c5-7e5bfd0a15e4" => "sss"
    "7342f212-083b-458d-8af8-24986bbb627d" => "ddd"
    "029c53ce-dc16-49fd-8d83-9d8270d9ff37" => "fff"
    "3add6a37-72e2-4054-853e-9ed8addbf3ea" => "ggg"
    "28f5a9ac-014e-4f22-bda8-e2d5b1f48273" => "hhh"
    "94fccb2c-d732-4369-9bf7-78925797e578" => "jjj"
    "5b494994-93f0-406e-b420-aceb7b6111d7" => "kkk"
    "22a7824a-c6eb-45e7-b9c5-e40c134e3ac8" => "lll"
  ]
}

Perfect. This collection is later passed in Form::selectto populate the select / option drop-down list.

I would like to add this collection to another key-value pair, where the key will be an empty string and the value will contain text such as "Select something."

I can add:

$foo[''] = 'Choose something…';

so i get

Collection {#506 ▼
  #items: array:10 [▼
    "9c436867-afe9-4234-a849-253aea4f602c" => "aaa"
    "d250102b-1370-40d0-99c5-7e5bfd0a15e4" => "sss"
    "7342f212-083b-458d-8af8-24986bbb627d" => "ddd"
    "029c53ce-dc16-49fd-8d83-9d8270d9ff37" => "fff"
    "3add6a37-72e2-4054-853e-9ed8addbf3ea" => "ggg"
    "28f5a9ac-014e-4f22-bda8-e2d5b1f48273" => "hhh"
    "94fccb2c-d732-4369-9bf7-78925797e578" => "jjj"
    "5b494994-93f0-406e-b420-aceb7b6111d7" => "kkk"
    "22a7824a-c6eb-45e7-b9c5-e40c134e3ac8" => "lll"
    "" => "Choose something…"
  ]
}

but I don’t know how I can transfer it as the first element of the collection . I just can't use array_mergeit because I'm dealing with an instance Illuminate\Database\Eloquent\Collection, not an array, so this answer will not work.

Any clues? Thanks.

+4
2
$foo = ['' => 'Choose something…'] + $foo->all();

$foo , :

$foo = collect(['' => 'Choose something…'] + $foo->all());

PR laravel, prepend. Laravel 5.1.24 , :

$foo = $this->fooRepository->all()->lists('name', 'id')->prepend('Choose something…', '');
+14

->prepend()

http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Collection.html#method_prepend

$foo->prepend('Choose Something')

a >


. 0 . -

$foo = $foo->reverse()->put('Choose Something')->reverse()

@Joseph Silber, , .

+1

Source: https://habr.com/ru/post/1614537/


All Articles