在 Laravel 中插入和更新类别的唯一验证

Unique validation with category for insert and update in Laravel

我有相关类别的项目列表(table 名称是: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

Laravel documention

唯一规则在这里对于类别明智不起作用,它验证 name 所有记录。

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);
}

如何验证具有相关类别的项目以在 Laravel 中插入和更新。

我想你需要这样的东西

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

UPD:更新现有行:

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

创建自定义验证Rule

php artisan make:rule UniqueCategoryName

并将您的验证规则更改为

use App\Rules\UniqueCategoryName;


'name' => ['required', new UniqueCategoryName($category_id)],

并在规则的 passes 方法中,针对 table

进行验证
<?php

namespace App\Rules;

use App\Item;
use Illuminate\Contracts\Validation\Rule;

class UniqueCategoryName implements Rule
{

    protected $category_id;

    public function __construct($category_id) {
        $this->category_id = $category_id;
    }

    public function passes($attribute, $value)
    {
        $items = Item::where([
                       ['category_id', $this->category_id],
                       ['name', $value]
                 ])->get();

        if ($items->count()) {
            return false;
        }

        return true;
    }

}

如果您的请求中有 category_id,那么这可能有效。

public function validateItems($requestAll){
   $id = isset($requestAll['id']) ? $requestAll['id'] : 'NULL'; //with PHP7 it could be $id = $requestAll['id'] ?? 'NULL';
   $categoryId = $requestAll['category_id']; //i don't know if it exists in your request.
   $rules = [
      'name' => 'required|unique:items,name,'.$id.',id,category_id,'.$categoryId,
      'category' => 'required'
   ];
   return Validator::make($requestAll, $rules);
}