Is there a way to handle inputs with the same name?

Hello Livewire Community,

i have a check-out page with a cart with one or multiple articles. For each article you have to fill in some data (url & comment).

With laravel i just did something like this to handle this data: name="url[]". But this isn’t possible with Livewire. Is there any workaround or something i can do?

I’ve used the key of the array, though, I am using wire:model.lazy. Setting the name like this should work similarly.

@foreach($items as $key => $item)
    <tr>
        <td>
            <input type="text" wire:model.lazy="items.{{ $key }}.name" />
            @invalidinput(['field' => "items.$key.name", 'errors' => $errors])@endinvalidinput
        </td>
    </tr>
@endforeach

Thanks for your reply!

How do you handle this in the Controller?

Sorry, just saw your reply. Do you mean a Laravel Controller or Livewire Component? I am using Livewire to handle the form submission so there is no Laravel Controller but it should work with a Controller too as Laravel supports array “dot” notation (reference).

Here is an example of what I am doing (trimmed down removing unnecessary code):

class MembershipPaymentsEdit extends Component
{
    public $items;

    // Called with wire:click
    public function save()
    {
        $organization = Organization::getByTypeAndNumberOrFail($this->type, $this->number);

        $this->runValidation();
        $this->saveOptions($organization);
    }

    private function saveOptions(Organization $organization)
    {
        foreach ($this->items as $item) {
            // Access like an array - $item['name']
        }
    }

    private function runValidation()
    {
        $this->validate(
            [
                'items.*.name' => 'required|string|max:50',
                'items.*.description' => 'required|string|max:100',
                'items.*.amount' => 'required|numeric|min:0',
            ],
            [
                'items.*.*.required' => 'This is required.',
                'items.*.*.string' => 'This must be a string.',
                'items.*.*.min' => 'The minimum is :min.',
                'items.*.*.max' => 'The max is :max characters.',
                'items.*.*.numeric' => 'This must be numeric.',
            ]
        );
    }
}

If you are using a Laravel Controller, you should just be able to do (assuming you are setting the name attribute on the input:

$items = $request->input('items');
1 Like