Home > Enterprise >  Check if name already exist in database but Id is not same in Laravel 6
Check if name already exist in database but Id is not same in Laravel 6

Time:03-06

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.

CodePudding user response:

In your validation, you can define a rule to check name unique with id like this

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

CodePudding user response:

Ignore the current ID in question when updating:


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

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

CodePudding user response:

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

  • Related