'Check if name already exist in database but Id is not same in Laravel 6

Properties Table

id name
1 abc
2 xyz

I want to check if the name exists during edit but if it is the same Property then ignore it.

When I want to insert using this code

$ruls = [
        'property_type' => 'required',
        'project_name' => 'required|unique:properties,name',
    ];
$request->validate($ruls, []);     

and I want to using same validation when property edit like

select name from properties where name = name and id != 1

Please help me to solve this issue.



Solution 1:[1]

Ignore the current ID in question when updating:


$ruls = [
        ...
        'project_name' => [required, Rule::unique('properties', 'name')
         ->ignore($id)],

    ];
$request->validate($ruls, []);

Solution 2:[2]

You can use the unique rule with ignore the id. Something like this:

$rules = [
    'property_type' => 'required',
    'property_name' => [
        'required',
         Rule::unique('properties', 'name')->ignore($property->id),
     ],
]

https://laravel.com/docs/9.x/validation#rule-unique

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali Raza
Solution 2 Can Celik