简体   繁体   中英

Laravel Form with multiple select

I have the following controller, which sends data to a Laravel Blade view:

Controller:

public function create()
{
    $schools = School::all()->sortBy('school_type');
    return view('invoices.create')->with([
        'schools' => $schools,
        'dayTypes' => $dayTypes,
    ]);
}

In that Laravel blade view there is a form:

<form method="GET" action="{{ route('invoices.choose-periods') }}">
    <div class="form-group {{ $errors->has('school') ? 'has-error' : '' }}">
        <label>School</label>
        <select id="school" class="form-control" name="school[]" multiple size="{{ $schools->count() }}" required>
            @foreach ($schools as $school)
                <option value="{{ $school->id }}">{{ $school->name }}</option>
            @endforeach
        </select>
        @if ($errors->has('school'))
            <span class="help-block">
                <strong>{{ $errors->first('school') }}</strong>
            </span>
        @endif
    </div>
        <button type="submit" class="btn btn-success btn-sm pull-right">Submit</button>
</form>

As you can see from the HTML, the form is a multi-select form, with the resulting data stored in a school[] array.

On submission of the form, I do a test die and dump on request('school') and see that for every option I have selected, the value seems to have been logged twice. For example, choosing only one option gives me:

array:2 [▼
  0 => "15"
  1 => "15"
]

Any ideas? Thanks!

I have only worked on laravel 5.7. Try this It is working for me. Since you are passing 2 objects

return view('invoices.create')->with([
    'schools' => $schools,
    'dayTypes' => $dayTypes,
]);

It is obvious you will get 2 errors.

In your controller change this

public function create()
{
$schools = School::all()->sortBy('school_type');
return view('invoices.create')->with([
    'schools' => $schools,
    'dayTypes' => $dayTypes,
]);
}

to this

public function create(){
$schools = School::all()->sortBy('school_type');
return view('invoices.create', ['schools' => $schools]),
]);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM