I am experimenting with Laravel Livewire and I came across a situation where the previous errors are displayed even though the form is successfully submitted.
Before hit Save
After hitting Save
Html segment of name
in blade file customer-new.blade.php
.
<div class="form-group">
<div class="border rounded-0 px-1">
<label class="mb-0" for="name">Name</label>
<input wire:model="name" type="text" class="form-control form-control-sm " id="customer-name" aria-describedby="customer-nameHelp">
</div>
@error('name') <span class="err-message">{{ $message }}</span> @enderror
</div>
and the Save button code:
<button
wire:click="store"
wire:loading.attr="disabled"
wire:target="store"
type="submit"
class="btn btn-sm btn-light">Save
</button>
store
method of CustomerNew.php:
public function store()
{
$this->validate([
'name' => 'required|max:80',
'street' => 'required|max:100',
'city' => 'required|max:40',
'dueAmount' => 'numeric|min:0'
]);
Customer::create([
'name' => $this->name,
'street' => $this->street,
'city' => $this->city,
'due_amount' => $this->dueAmount,
]);
session()->flash('message', 'Customer was saved');
$this->clear();
}
and the clear()
method is like:
public function clear() {
$this - > name = '';
$this - > street = '';
$this - > city = '';
$this - > dueAmount = 0;
}
According to docs https://laravel-livewire.com/docs/input-validation,
You need to reset the validations whenever you want
Direct Error Message Manipulation The validate() and validateOnly() method should handle most cases, but sometimes you may want direct control over Livewire's internal ErrorBag.
Livewire provides a handful of methods for you to directly manipulate the ErrorBag.
From anywhere inside a Livewire component class, you can call the following methods:
$this->addError('email', 'The email field is invalid.'); // Quickly add a validation message to the error bag. $this->resetErrorBag(); $this->resetValidation(); // These two methods do the same thing. The clear the error bag. // If you only want to clear errors for one key, you can use: $this->resetValidation('email'); $this->resetErrorBag('email'); $errors = $this->getErrorBag(); // This will give you full access to the error bag, // allowing you to do things like this: $errors->add('some-key', 'Some message');
HINT
I am using the reset methods on hydrate function like following
...
public function hydrate()
{
$this->resetErrorBag();
$this->resetValidation();
}
...
You should reset the public properties by using the livewire's reset
method. Delete your $this->clear()
method definition and replace it with the following:
$this->reset('name', 'street', 'city', 'dueAmount');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With