phplaravellaravel-livewire

Laravel Livewire rules with unique attribute


In my AddUser Livewire component, I have the following rule:

#[Rule('required|max:50|unique:users,name')]
public $name;

Which of course does its job. But when I'm trying to update a user in the database I have the following rule:

#[Rule('required|max:50|unique:users,name,' . $this->user?->id)]

I am getting an error with this:

Constant expression contains invalid operations

I am trying to understand what I am doing wrong, since this is what I would do normally in Laravel, and I cannot find anything online about this. Any explanation and/or solution to make it work without having to use public function rules()?


Solution

  • I did some research and found that when using the #[Rule()] format is not capable of performing the ignore unique rule. So you have to use the Rule object.

    Livewire docs for Rule object.

    Here is a good GitHub discussion related to your problem.