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

19,162

Solution 1

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

If your $foo must be a collection instance, simply wrap it in a collection again:

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

I submitted a PR to laravel to allow you to pass a key to prepend. If you're using Laravel 5.1.24 or newer, you can now do this:

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

Later versions of Laravel have renamed the lists method to pluck. If you're using relatively modern version of Laravel, use pluck instead:

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

Solution 2

Try using ->prepend()

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

$foo->prepend('Choose Something')


This won't give the correct result. The index would be 0 instead of an empty string. Instead you could try something like this

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

But using @Joseph Silber answer is probably better.

Share:
19,162
Matt Komarnicki
Author by

Matt Komarnicki

Hi there! I'm Matt - Software Architect who crafts highly scalable, multi-tenant, SaaS and cloud-based applications. I am an easy-going guy who loves to work with creative individuals on challenging projects using suitable technologies. I like to share my knowledge with others, mentor, inspire and collaborate with my work mates. While I prefer to stick within realm of backend code, I do enjoy working on a visual layer of each project as well. I consider myself a person with decent graphic taste in terms of UX/UI and styling things in general. Find out more at mattkomarnicki.com.

Updated on June 17, 2022

Comments

  • Matt Komarnicki
    Matt Komarnicki almost 2 years

    I'm fetching something from 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 into Form::select to populate select / option dropdown.

    I would like to prepend this collection with another key-value pair where key will be empty string and value will contain text like "Choose something".

    I can append:

    $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 no idea how I can move it as the first element of the collection. I simply cannot use array_merge because I'm dealing with instance of Illuminate\Database\Eloquent\Collection rather than array so this answer won't work.

    Any hints? Thanks.

  • Joseph Silber
    Joseph Silber over 8 years
    This will set the key to 0. The OP wants the key to be an empty string.
  • EspadaV8
    EspadaV8 over 8 years
    Yep, you're absolutely correct. Could do something like $foo->reverse()->put(‘Choose Something’)->reverse() instead
  • Matt Komarnicki
    Matt Komarnicki over 8 years
    Thanks Joseph. This was very helpful. Only thing I had to change was to use Illuminate\Support\Collection.
  • Joseph Silber
    Joseph Silber over 8 years
    @slick - what do you mean? Where, what and why did you have to change?
  • Matt Komarnicki
    Matt Komarnicki over 8 years
    later, inside the place that was expecting that $foo collection. :) All good. Don't worry!
  • Matt Komarnicki
    Matt Komarnicki over 6 years
    Now it's worth mentioning that lists has been deprecated and pluck should be used instead.
  • Solivan
    Solivan over 5 years
    thanks, Is there any better way like "array_unshift()" in arrays?
  • Rox
    Rox over 4 years
    ->prepend('Choose something…', ''); worked amazingly!