I have created a dependant dropdown with livewire like this:
class CreateAppointment extends Component
{
public $doctorCategories;
public $doctors;
public $selectedDoctorCategory = NULL;
public function mount(){
$this->doctorCategories = Doctor_Categories::all();
$this->doctors = collect();
}
public function updatedSelectedDoctorCategory($doctor_type_ID)
{
if(!is_null($doctor_type_ID)){
$this->doctors = Doctor_Categories::with('doctors')->find($doctor_type_ID);
}
}
}
And this is in my blade file:
<div >
<label for="doctor_categories" >Doctor Categories</label>
<div >
<select wire:model="selectedDoctorCategory" >
<option value="">Choose category</option>
@foreach($doctorCategories as $cat)
<option value="{{ $cat->id }}">{{ $cat->doctor_category }}</option>
@endforeach
</select>
</div>
</div>
@if (!is_null($selectedDoctorCategory))
<div >
<label for="doctor" >Doctor</label>
<div >
<select name="doctor_id">
<option value="" selected>Choose Doctor</option>
@foreach($doctors->doctors as $doctor)
<option value="{{ $doctor->id }}">{{ $doctor->name }}</option>
@endforeach
</select>
</div>
</div>
@endif
</div>
It works well but when i select "Choose category" again it throws an error saying attempted to read property doctors on null.How can i avoid this?
CodePudding user response:
The issue here is, that livewire does not apply the TrimStrings
and ConvertEmptyStringsToNull
middlewares on its requests. This is by design and is not a bug. It can be reintroduced (see the comments to the linked issue) but I advise caution doing so. With select it should work fine, but with input it can mess things up.
Instead of checking for is_null
, check for empty
and you should be fine.