I have the code below that is a resume of the process to create a new conference. To create a new conference is ncessary that the user introduce some info like the conference name, etc. The user also needs to introduce between 1 and 3 categories for the conference.
So there is a select element using select2 plugin so the user can select the categories:
<div class="form-row">
<div class="form-group col-lg-6">
<label for="categories">Category</label>
<select id="tag_list" required multiple class="form-control" value="{{ old('categories') }}" name="categories" id="categories">
@foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
</div>
</div>
Then the laravel code to store the conference info and also the categories of the conference in the conference_category table since there is a many to many relationship between confernece and category:
public function store(Request $request)
{
$this->validate($request, [
'conference_name' => 'required|max:255|string',
'conference_categories' => 'required|array|between:1,3|integer',
]);
$conference = Conference::create([
'name' => $request->conference_name,
]);
$conference->categories()->attach($request->conference_categories);
}
The select2 JS:
$(function() {
$('#tag_list').select2({
placeholder: '',
dropdownAutoWidth: 'true',
width: '100%'
});
});
Errors
- If the user selects more than one category in the $request output just appears the id of one category
- And it appears a laravel validation error after submit the form "The conference categories must be an array. "
Do you know where can be the issue?