Search code examples
phplaravellaravel-5laravel-validation

Unique validation with category for insert and update in Laravel


I have list of items with related categories (table name is : items)

--- id ------ category_id ----- name
--- 1 ------- 1 ---------------- aa  --> Valid
--- 2 ------- 1 ---------------- bb  --> Valid
--- 3 ------- 2 ---------------- aa  --> Valid
--- 4 ------- 2 ---------------- bb  --> Valid
--- 5 ------- 1 ---------------- aa  --> InValid because same name exist in same category
--- 6 ------- 2 ---------------- bb  --> InValid because same name exist in same category

As In Laravel documention

Unique rule will not work here as for category wise, It validates name for all records.

public function validateItems($requestAll){
    $id = isset($requestAll['id']) ? ','.$requestAll['id'].',id':'';
    $rules = [
        'name' => 'required|unique:items,name'.$id,
        'category' => 'required'
    ];
    return Validator::make($requestAll, $rules);
}

How to validate items with related categories for insert and update in Laravel.


Solution

  • I think you need something like

    'name' => Rule::unique('items')->where(function ($query) use ($categoryId) {
        return $query->where('category_id', $categoryId);
    }),
    

    UPD: For update existing row:

    'name' => Rule::unique('items')->ignore($existingRecordId)->where(function ($query) use ($categoryId) {
        return $query->where('category_id', $categoryId);
    }),