0

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 names 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 set name = product, tags.updated_at = 2020-10-08 02:35:52 where id = 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"
}
Dani Fadli
  • 353
  • 4
  • 18

1 Answers1

0

I don't think you need to do all this just to check unique validation on the same model.

Have you tried this?

if(Request::method() == 'PUT') $rules = array_merge($rules, [
        'name' => [
            'required',
            'string',
            'max:255',
            'unique:tags',
])

This should work just fine. As mentioned in the docs here If you are checking all conditions for the same model then you don't to check the where condition explicitly.

AbhimanuSharma
  • 453
  • 1
  • 8
  • 21