Skip to content

Instantly share code, notes, and snippets.

@oliuz
Forked from paperscissors/FieldRepeater.php
Created November 6, 2023 18:28
Show Gist options
  • Save oliuz/edbc552e85af65e47e5db4ff972c76a7 to your computer and use it in GitHub Desktop.
Save oliuz/edbc552e85af65e47e5db4ff972c76a7 to your computer and use it in GitHub Desktop.
Laravel Livewire 3 Field Repeater
<div>
@foreach($rows as $index => $row)
<div class="flex items-center space-x-4 mb-3" wire:key="min{{ $index }}">
<input
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline h-10"
type="number" wire:model="rows.{{ $index }}.min" placeholder="Min">
<input
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline h-10"
type="number" wire:model="rows.{{ $index }}.max" placeholder="Max">
<input
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline h-10"
type="text" wire:model="rows.{{ $index }}.price" placeholder="Price">
<button
class="bg-red-400 hover:bg-red-700 text-white py-2 px-4 rounded focus:outline-none focus:shadow-outline h-10"
wire:click="removeRow({{ $index }})">Remove
</button>
</div>
@endforeach
<button wire:click="addRow"
class="bg-gray-400 hover:bg-gray-700 text-white py-1 px-2 text-sm rounded focus:outline-none focus:shadow-outline">
Add Row
</button>
</div>
<?php
namespace App\Livewire;
use Livewire\Component;
class FieldRepeater extends Component
{
public array $rows = [];
public string $field;
protected $listeners = ['updateRows'];
public function mount($field, $initialRows = [])
{
$this->field = $field;
$this->rows = $initialRows;
}
public function updated($propertyName)
{
ray('updated', $propertyName);
$this->dispatch('update-rows', field: $this->field, rows: $this->rows);
}
public function addRow()
{
$this->rows[] = ['min' => '', 'max' => '', 'price' => ''];
$this->dispatch('update-rows', field: $this->field, rows: $this->rows); // Emit an event to the parent
}
public function removeRow($index)
{
unset($this->rows[$index]);
$this->rows = array_values($this->rows);
$this->dispatch('update-rows', field: $this->field, rows: $this->rows); // Emit an event to the parent
}
public function render()
{
return view('livewire.field-repeater');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment