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

后端 未结 7 732
情深已故
情深已故 2021-02-01 04:40

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 ar

7条回答
  •  孤独总比滥情好
    2021-02-01 04:51

    @SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

    On your controller

    $dogs = Dog::lists('name', 'id');
    

    On customer create view you can use.

    {{ Form::label('dogs', 'Dogs') }}
    {{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
    

    Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

    {{ Form::label('dogs', 'Dogs') }}
    {{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
    

    Update For Laravel 5.1

    The lists method now returns a Collection. Upgrading To 5.1.0

    {!! Form::label('dogs', 'Dogs') !!}
    {!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
    

提交回复
热议问题