Answer the question
In order to leave comments, you need to log in
The Laravel validation rule does not work: ignoring the check for uniqueness (unique) when updating data. How to fix?
When creating the admin section for editing product categories, there were problems with validation when updating data, namely: ignoring the validation rules for the unique value of the slag field when updating data. In the categories
database table , for CNC links, a “slag” field has been created - with a check for uniqueness In the UPDATE
method of the resource controller, a number of rules for validation are prescribed, including for checking for the uniqueness of the slag field, ignoring the current value for updating data.
$table->string('slug')->unique();
public function update(Request $request, $id)
{
$category = Category::find($id);
$messages = [
'name.required' => 'Поле "Наименование категории" обязательно для заполнения',
'slug.required' => 'Поле "ЧПУ категории" обязательно для заполнения',
'slug.unique' => 'Данные в поле "ЧПУ категории" должны быть уникальными',
.....
];
$this->validate($request, [
'name' => 'required',
'slug' => 'required|unique:categories,slug,'.$category->slug,
....
],$messages);
'slug' => 'required|unique:categories,slug,'.$category->slug
//То есть
//slug' => 'required|unique:таблица,поле,текущее_значение'
Answer the question
In order to leave comments, you need to log in
Both examples are from the working draft
public function rules()
{
return [
'name' => 'required|string|min:2|max:30',
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($this->id)],
'password' => 'min:8',
'role' => 'required'
];
}
}
public function rules()
{
return [
'title' => ['required', Rule::unique('vh_nodes', 'title')->ignore($this->id)],
'url' => 'required',
'login' => 'required',
'password' => 'required',
];
}
You don't need to concatenate the value itself to the validation rule.
It is enough to specify the table and the field.
You can also omit the indication of the table column if the name of the checked field matches the column
'slug' => 'required|unique:categories,slug'
'slug' => 'required|unique:categories'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question