【问题标题】:Laravel unique field validationLaravel 唯一字段验证
【发布时间】:2019-03-24 23:21:07
【问题描述】:

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

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

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

【问题讨论】:

  • 通常,我对新行和现有行使用两种不同的验证器表达式。但我希望有人能做得更好。
  • 为什么不使用数组表示法进行验证,在非更新情况下添加唯一键
  • @BagusTesa 如何区分表单方法?
  • @ThomasMoors 示例?
  • @Ronny-AndréBendiksen,在使用Resource Controller 时,您有两种方法,一种用于存储另一种用于更新。 Thomas 方法会以这种方式使用验证规则$validationRule = ['product_no' => ['nullable', Rule::unique('products', 'product_no')->ignore(auth()->user()->id, 'user_id')]]。我没有尝试过 Thomas 的建议,只是一个粗略的猜测.. 似乎是新功能。

标签: laravel validation laravel-5.7


【解决方案1】:

根据要求提供示例

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

然后那个独特的看起来像这样

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 2018-08-09
    • 1970-01-01
    • 2014-03-09
    • 2015-05-15
    • 1970-01-01
    • 2023-03-20
    • 2018-07-29
    相关资源
    最近更新 更多