I've searched for some questions related to my problem here and have applied them. But the result still not what I wanted for. Here are the references:
Laravel conditional unique validation
Laravel | Unique validation where clause
In my case, I want to validate the name
field in the request to be unique when updating, only if the requested value is different from the previous stored name
in the database. Here is my current code.
if(Request::method() == 'PUT') $rules = array_merge($rules, [
'name' => [
'required',
'string',
'max:255',
Rule::unique('tags')->where(function ($q) use ($request) {
$q->where('name', '!=', strtolower($request['name']));
})
]
]);
In my database, I have some rows of data. The name
s of those data are product, event, and campaign. When I want to update the campaign name with product in the request, the validation doesn't make this unique. It returns
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'product' for key 'tags_name_unique' (SQL: update
tags
setname
= product,tags
.updated_at
= 2020-10-08 02:35:52 whereid
= 14)
I hope I explained it well. Anyone can help me? Thanks in advance.
Edit #1:
My tags
table migration:
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable()->unique();
$table->text('description')->nullable();
$table->timestamps();
});
}
Edit #2:
Here is my request payload from Postman in JSON.
{
"id": 14,
"name": "product",
"description": "Descriptions"
}