I'm working with Livewire components in a Laravel application, and I'm encountering issues when handling nullable numeric inputs (e.g., integers, floats). Specifically, when a user clears a numeric input field, Livewire assigns an empty string ("") to the property. This behavior can lead to type errors if the property is type-hinted as a numeric type (int, float, etc.).
class MyComponent extends Component
{
public ?int $numericValue = null;
public function updated($propertyName)
{
$this->validateOnly($propertyName, [
'numericValue' => 'nullable|integer',
]);
}
public function render()
{
return view('livewire.my-component');
}
}
When the numericValue input is cleared, Livewire assigns an empty string, resulting in a type error because ?int cannot be an empty string.
In order to resolve the issue when Livewire assigns an empty string to numericValue
when the input is cleared, you can handle the conversion in the updated($propertyName)
method by checking if the value is an empty string and then setting it to null
like this
public function updated($propertyName)
{
// Convert empty string to null for numericValue
if ($propertyName === 'numericValue' && $this->numericValue === '') {
$this->numericValue = null;
}
$this->validateOnly($propertyName, [
'numericValue' => 'nullable|integer',
]);
}
Try this, I think it will work.