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

时间:2018-02-05 11:14:06

标签: php laravel laravel-5 laravel-validation

我有相关类别的项目列表(表名是: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中验证具有相关类别的项目以进行插入和更新。

3 个答案:

答案 0 :(得分:4)

我认为你需要像

这样的东西
'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);
}),

答案 1 :(得分:1)

如果您的请求中有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);
}

答案 2 :(得分:0)

创建自定义验证Rule

php artisan make:rule UniqueCategoryName

并将验证规则更改为

use App\Rules\UniqueCategoryName;


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

并在规则的pass方法中,对表进行验证

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

}