On laravel / livewire site item model has unique "title" field and I added unique in validate attribute
class ItemEditor extends Component
{
#[Validate('required|string|min:3|max:255|unique:items,id')]
public string $title = '';
But it does not work in method :
public function store(): void
{
$this->validate();
try {
DB::beginTransaction();
$item = Item::create([
'title' => $this->title,
...
]);
Checking sql under telescope I see statement :
SELECT count(*) AS aggregate
FROM `items`
WHERE `id` = 'Title 5'
But anyway validate for unique rule does not work(the rest of rules work ok).
Some syntax error for unique rule of validate?
"laravel/framework": "^11.31",
"laravel/jetstream": "^5.3",
"livewire/livewire": "^3.0",
Thanks in advance!
You are specifying that the id
column should be unique, that is - it's checking to see if there are any of the value you have in your $title
property that exists in the id
column of your items
table.
If you are creating records (and not updating them), you don't need to specify a ignore-value, and it should work with what you have (minus the ,id
at the end)
#[Validate('required|string|min:3|max:255|unique:items')]
However if you are updating an existing record, you need to use the rules()
method to specify which record to "ignore" in the check for uniqueness (so you ignore the current record, thereby allowing to update the record, but keeping the same title).
protected function rules()
{
return [
'title' => [
'required',
'string',
'min:3',
'max:255',
'unique:items,id'
\Illuminate\Validation\Rule::unique('items')->ignore($this->itemId),
],
];
}