Search code examples
phplaravellaravel-5.3laravelcollective

Populate multiple select field in Laravel


I try to populate a multiple select field in laravel like this:

{{ Form::select('maisons[]', $maisons, $partenaire->maisons->pluck('id'), ['class' => '', 'multiple' ]) }}

The option are not select in the dropdown. I then tried this:

$partenaire->maisons->pluck('id')

and it returns an array: [1,2,3] (example)

I then tried to put the array manually in the field like this:

{{ Form::select('maisons[]', [1,2,3], ['class' => '', 'multiple' ]) }}

The previous line returns the select field with the select iptions.

What is wrong then ?

More information, here is dd($partenaire->maisons->pluck('id'))

Collection {#671 ▼
  #items: array:6 [▼
    0 => 3
    1 => 8
    2 => 12
    3 => 13
    4 => 17
    5 => 21
  ]
}

and dd($maisons)

Collection {#378 ▼
  #items: array:300 [▼
    1 => "Test 1"
    2 => "Test 2"
    3 => "Test 3"
    4 => "Test 4"
    5 => "Test 5"
    6 => "Test 6"
    ...
  ]
}

Solution

  • From Laravel version 5.3 => ...

    pluck()
    

    returns a collection and therefore you need to append toArray() at the end like this:

    $partenaire->maisons->pluck('id')->toArray()
    

    and that should return you the options in your select box!