So I’m creating an application where I can create a new group with a name, a dropdown list to add a member, a minimum age, a maximum age, and whether the group is active or not.
However I’m getting the validation error ‘member is required’ when I’m choosing a member from my dropdown list, and when I choose a member from my dropdown list I want it to be sent to the database and added to the new group I just created together with the all other input values.
Here is my dropdown code
<x-tmk.form.select wire:model="newGroup.member_id" id="member_id" class="block mt-1 w-full">
<option value="">Select a member</option>
@foreach ($members as $member)
<option value="{{ $member->id }}">{{ $member->name }}</option>
@endforeach
</x-tmk.form.select>
Here is my controller code to create a new group:
public function createGroup()
{
$this->validate();
$group = Group::create([
'id' => $this->newGroup['id'],
'name' => $this->newGroup['name'],
'member_id' => $this->newGroup['member_id'],
'min_age' => $this->newGroup['min_age'],
'max_age' => $this->newGroup['max_age'],
'active' => $this->newGroup['active'],
]);
$group->groupmember()->create([
'member_id' => $this->newGroup['member_id'],
]);
$this->showModal = false;
$this->dispatchBrowserEvent('swal:toast', [
'background' => 'success',
'html' => "The group <b><i>{$group->name}</i></b> has been added",
]);
}
And here is my controller code for my render() method:
public function render()
{
$members = Member::orderBy('name')->get();
$query = Group::orderBy('id');
if ($this->search) {
$groups = $query->searchGroupName($this->search)->paginate($this->perPage);
} else {
if ($this->showActiveOnly) {
$groups = $query->where('active', 1)->paginate($this->perPage);
} else {
$groups = $query->where('active', 0)->paginate($this->perPage);
}
}
return view('livewire.admin.group-classification', compact('groups', 'members'))
->layout('layouts.projectphp-layout', [
'title' => 'Groepen',
'description' => 'Hier kan je de groep indelingen bekijken.'
]);
}
I’m using laravel 9.52 and PHP 8.1
Thanks in advance
2
Answers
Add deafult value in your
mount()
functionLivewire does not listen to
selected
attributes in HTML when you are usingwire:model
, because it will overwrite it with the value from the component. Therefor, setwire:key
to youroption
like below,To set a value that is bound through
wire:model
, you need to set the value in the component. So in themount()
method, you can do