Laravel – Livewire V3 Force Update of Input

  • Post category:Snippets

Sometimes in Livewire v3, certain input fields (e.g. select) do not update when the model is changed. To resolve this you can add a wire:key to the input with specific property of the model it is wired to.

For example, in the case of a select:

<select wire:model.live="customer" 
wire:key="customer-select-{{ $customer->id ?? '' }}">
PHP

This is described in the following PR.

Or in the case of file inputs:

<input type="file" id="file_input" wire:model.live="files" 
wire:key="files-{{ count($filesAdded) }}">
PHP

In the above, lets say that the uploaded method is called when a file is uploaded which processes the files and adds it to the $filesAdded variable and database, and then clears the files to an empty array. Whenever a file is uploaded and added to the $filesAdded property (i.e. an array or collection), the count of the $filesAdded changes and so it updates the input field to clear it since the files is reset to an empty array.