Laravel唯一字段验证

Laravel唯一字段验证

问题描述:

我有一个产品模型,其中有一个用于产品编号的文本输入字段.在我的Laravel应用程序中,我验证此字段对于该特定用户而言是唯一的.因此,两个用户可以具有相同的产品编号,但一个用户不能重复.到目前为止,验证规则在添加新产品时有效:

I have a Product model with a text input field for the product number. In my Laravel application I validate this field to be unique to that specific user. So two users can have a same product number, but one user cannot have duplicate. So far the validation rules work when adding new products:

'product_no' => 'nullable|unique:products,product_no,NULL,id,user_id,' . auth()->user()->id

但是,当编辑同一产品时,验证失败.可能是因为它已经存在.我不确定如何在验证中排除现有ID.有什么想法吗?

However, when editing the same product, the validation fails. Probably because it already exists. I am not sure how to exclude the existing ID in the validation. Any ideas?

所要求的示例

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class Request1 extends FormRequest
{
    private $rules;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    public function __construct()
    {
         parent::__construct();
         $this->rules = [
            'password' => [
                'nullable',
            ]
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return $this->rules;
    }
}

然后具有唯一性的那个就这样

And the one with unique looks like this then

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class Request2 extends Request1
{

    public function __construct()
    {
         parent::__construct();
         $this->rules[] = 'unique:products,product_no,NULL,id,user_id,' . auth()->user()->id';  
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return $this->rules;
    }
}