Laravel唯一字段验证 [英] Laravel unique field validation

查看:91
本文介绍了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;
    }
}

这篇关于Laravel唯一字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆