Search code examples
phplaravellaravel-livewire

Check checkboxes in Laravel Livewire edit form


I have a Gebruikers model (Dutch for users) and a Ateliers model (Dutch for workshop). There is a many to many relationship between them.

When saving a new Gebruiker you can check the Ateliers the gebruiker is attending.

In the Livewire 'controller':

 public $selectedAtelier = [];
 public $gebruiker;

 public function saveGebruiker(){



$nieuwegebruiker = Gebruiker::create([
                'first' => $this->gebruiker['first'],
                'last' => $this->gebruiker['last'],
            
        ]);

        $nieuwegebruiker->ateliers()->sync($this->selectedAtelier);
}

In the component:

<input type="text" wire:model="gebruiker.first">
<input type="text" wire:model="gebruiker.last">
 @foreach ($ateliers as $atelier)
  <input wire:model="selectedAtelier" value="{{ $atelier->id }}" 
       type="checkbox" 
      id="{{ $atelier->id }}"><label>{{$atelier-name}}</label>
 @endforeach

This works fine. the gebruiker is saved in the Gebruiker table and the ateliers are saved in the pivot table.

When editing the specific gebruiker, how can I make the checkboxes for the ateliers that are saved in the pivot table checked?


Solution

  • I'll try to reproduce some of the logic you need based in the code you share here

    // in component
    
    public function someLoadMethodOnEdit() 
    {
       $this->selectedAtelier = $this->gebruiker->ateliers()->pluck('id')->map(
                            function($group) {
                                return strval($group);
                            })->toArray();
    }
    
    // in blade
     @foreach ($ateliers as $atelier)
      <input wire:model="selectedAtelier" value="{{ $atelier->id }}" 
           type="checkbox" @if(in_array($atelier->id,$selectedAtelier)) checked @endif
          id="{{ $atelier->id }}" wire:key="aterlier-checkbox-{{ $atelier->id }}"><label>{{$atelier-name}}</label>
     @endforeach