Using Laravel, I have created an updatable form. One of these fields is a multi-select dropdown. This field should display all locations linked to a given project. So the user can see which location he selected and if he wants to update. But on this moment, there is noting selected. Bellow you will find the code.
The controller send the data to the blade template like this:
public function edit(Project $project)
{
$locations = Location::where('project_id', $project->id)->get();
return view('projects.edit', [
'project' => $project,
'location' => $locations,
'edit' => true
]);
<select multiple class="form-control" name="locations[]">
<option {{old('location',$project->location) == "Room A1" ? 'selected' : ''}} value="Room A1">Room A1</option>
<option {{old('location',$project->location) == "Room C1" ? 'selected' : ''}} value="Room C1">Room C1</option>
<option {{old('location',$project->location) == "Room D2" ? 'selected' : ''}} value="Room D2">Room D2</option>
<option {{old('location',$project->location) == "Room A3" ? 'selected' : ''}} value="Room A3">Room A3</option>
<option {{old('location',$project->location) == "Room G3" ? 'selected' : ''}} value="Room G3">Room G3</option>
</select>
This field should normally display all the values selected. However, this isn't the case. For example: For project with id 1, Room A1 and Room D2 should be selected in dropdown.
The code is working for the single dropdown but not for the multi-select dropdown. I don't quite understand why. Could you help me on the way? Thanks.
The data that should be displayed in this multi-select dropdown is stored in the database. Presented in this table:
+----+------------+----------+--+
| id | project_id | location | |
+----+------------+----------+--+
| 1 | 1 | Room A1 | |
| 2 | 1 | Room D2 | |
| 3 | 2 | Room A1 | |
+----+------------+----------+--+
$locations = Location::where('project_id', $project->id)->get();
Returns a Illuminate\Support\Collection
Object. You can pluck the locations from the collection like
$selectedLocations = $locations->pluck('location')->toArray();
and then check if location exists in the $selectedLocations
array like
<option {{(old('location') == "Room A1" || in_array("Room A1", $selectedLocations) ? 'selected' : ''}} value="Room A1">Room A1</option>