V
V
Vitalionus2020-01-16 19:24:54
Laravel
Vitalionus, 2020-01-16 19:24:54

How to properly validate for uniqueness if another field is not equal?

There is a table of tags with columns name and post_id.

How to check if two fields are unique when updating?

$request->validate([
     'tag' => 'unique:tags,name,' . $tag->name,
])

But only to check the uniqueness by two fields, by name and post_id.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kovalchuk, 2020-01-16
@mamut

must be ignored if post_id is not the same

$request->validate([
'tag' => Rule::unique('tags', 'name')->where(function ($query) {
    return $query->where('post_id', $request->post_id);
})
])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question