Home » Php » php – Laravel validation rule fails when trying to update the same record with no changes

php – Laravel validation rule fails when trying to update the same record with no changes

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’ve got a table called Sides which consists of id, name, side_category_id and some other fields not important at the moment.

I wanted to validate that when creating a new side record, the record doesn’t exist already. So, let’s say I’ve got in the database a record such as:

id: 1
name: Salad
side_category_id: 3

If I try to insert a new record with name = 'salad' and side_category_id = 3 then the creation must fail and return an error.

I’ve achieved this by using the following rule:

$rules = [
   'name'             => 'required',
   'side_category_id' => 'required|exists:side_categories,id|unique:sides,side_category_id,NULL,id,name,' . $this->request->get('name')
]

So far so good. It works as it’s supposed to. But now it’s returning an error if I want to edit a record and save it without any modifications and this is not my desired outcome.

If I try to update the record with no modifications it should succeed. How can I update my rule to achieve this?

How to&Answers:

you can use Rule::unique()

for create use like this

$rules = [
   'name'             => ['required'],
   'side_category_id' => ['required',Rule::unique('sides', 'name')->where(function ($query) use($category_id) {
    return $query->where('side_category_id', $category_id);
}),Rule::exists('side_categories')]
]

for update

$rules = [
       'name'             => ['required'],
       'side_category_id' => ['required',Rule::unique('sides', 'name')->where(function ($query) use($category_id) {
        return $query->where('side_category_id', $category_id);
    })->ignore($id),Rule::exists('side_categories')]
    ]
//$id should be you parameter