Livewire Update Validation on Unique Field
Hello!
How do you ignore an id while validating a unique field in livewire? I'm trying to update a user.
Here's my livewire class:
public User $user;
public $name;
public $username;
public $email;
protected $rules = [
'name' => 'required|string|max:255',
'username' => 'required|min:6|max:255|alpha_dash|unique:users,username,' . $this->user->id,
'email' => 'required|string|email|max:255|unique:users,email,' . $this->user->id
];
public function updateForm()
{
$validatedData = $this->validate();
$this->user->update($validatedData);
session()->flash('message', 'User successfully updated.');
}
I'm getting a Constant expression contains invalid operations error if I'll include $this->user->id in protected $rules = [].
I solve it by creating a rules function.
protected function rules()
{
return [
'name' => 'required|string|max:255',
'username' => 'required|min:6|max:255|alpha_dash|unique:users,username,' . $this->userID,
'email' => 'required|string|email|max:255|unique:users,email,' . $this->userID
];
}
public function updateForm()
{
$validatedData = $this->validate();
$this->user->update($validatedData);
session()->flash('message', 'User successfully updated.');
}
You could have used the protected function for dynamic rules
protected function rules()
{
return [
'name' => 'required|string|max:255',
'username' => 'required|min:6|max:255|alpha_dash|unique:users,username,' . $this->user->id,
'email' => 'required|string|email|max:255|unique:users,email,' . $this->user->id
];
}
Livewire invokes this function to set rules dynamically this way.
(More about that here: https://laravel-livewire.com/docs/2.x/input-validation#introduction)
For all of those searching on this trying to use the ignore() fluent structure in Livewire, make sure it's wrapped in a rules() function first - then:
protected function rules(){
return [
'vendor.display_name' => ['required',
'min:3',
Rule::unique('vendor')->ignore($this->vendor->id)],
'vendor.company_name' => 'nullable|min:3',
'vendor.check_name' => 'nullable|min:3',
...
Please or to participate in this conversation.