Laravel - Form Input - Multiple select for a one to many relationship

datavoredan picture datavoredan · Jul 8, 2014 · Viewed 120.7k times · Source

One of the requirements in an application that I am building is for a form input which takes in a varying number of items for a single field. For instance, sports that I play are ('Soccer','Tennis','Croquet').

There are a finite number of sports one can play (arguably), so these items should be selected from a "drop down" type list in the form input.

Downstream of this form will be two tables which have a one-to-many relationship. So from the above, the "user" table would have a single row, while the "user_sports" table would have three rows. These would then be linked by the id field in the user table.


I have not been able to find the sort of functionality where this can be achieved in the documentation (perhaps I am not searching for the correct thing). Below was the closest that I found, but is only for selecting a single item from a drop down list.

http://laravel.com/docs/html#drop-down-lists


Is there a workaround out there that will enable me to get this form element up and running using the Laravel framework?

Alternatively, are there other ways that this sort of functionality can be achieved, without damaging the user experience?

Answer

SamMonk picture SamMonk · Jul 8, 2014

I agree with user3158900, and I only differ slightly in the way I use it:

{{Form::label('sports', 'Sports')}}
{{Form::select('sports',$aSports,null,array('multiple'=>'multiple','name'=>'sports[]'))}}

However, in my experience the 3rd parameter of the select is a string only, so for repopulating data for a multi-select I have had to do something like this:

<select multiple="multiple" name="sports[]" id="sports">
@foreach($aSports as $aKey => $aSport)
    @foreach($aItem->sports as $aItemKey => $aItemSport)
        <option value="{{$aKey}}" @if($aKey == $aItemKey)selected="selected"@endif>{{$aSport}}</option>
    @endforeach
@endforeach
</select>