I have a blade form in which there is a field <select>
with multiple
activated, to be able to select more than one option. Of course, the form goes to a controller where it is validated. The point is that if it doesn't pass validation and the control is returned to the form, the options that were selected must remain selected, through the helper old()
.
Now, since it is a multiple, the data has been passed as an array, and it returns as an array, so that old()
, if we return from validation, it contains an array with the selected options. I have put it like this:
<select class="form-control" id="city_ids" name="city_ids[]" size="10" multiple>
<option value="00" class="sin-asignacion" {{ old('city_ids') ? ((@in_array('00', old('city_ids'))) ? " selected":"") : " selected" }}>CREAR SIN ASIGNAR</option>
<option value="" disabled></option>
@foreach ($cities as $city)
<option value="{{ $city->id }}" {{ (@in_array($city->id, old('city_ids'))) ? " selected":"" }}>
{{ $city->name }}
</option>
@endforeach
</select>
As you can see, I must look for each option in the matrix, with in_array
, to see if it is selected or not. The problem is that the first time the form is loaded, before going through validation, old('city_ids')
is null
, so using it in_array
throws an exception. I have solved it, as you can see in the code, using @
, so that the exception is not thrown. Work, it works, but it seems a bit botched to me. I'm sure blade, or the old()
, has some more elegant, more Laravel-style output. Have any of you solved this in a "cleaner" way? Can you give me some idea?
You could also avoid the error by passing the default value as the second parameter when the helper
old('city_ids')
returnsnull
.For this case it would be a
array
void .