【问题标题】:Rule::unique not working while update | LaravelRule::unique 在更新时不工作 |拉拉维尔
【发布时间】:2021-05-05 17:11:10
【问题描述】:

您好,我正在使用 Request 来验证我的表单。

listingId = 20
categoryType ='listing-category'

我尝试了两种方法来验证表单。首先是

'title' => 'required|min:2|max:255|unique:terms,title,'.$listingId.',id,type,'.$categoryType,

第二个是

if($this->method() != 'PUT')
    {
        $uniqueTitleValidation = Rule::unique('terms')->where('type', $categoryType);
    }
    else
    {
        $uniqueTitleValidation = [];
        $uniqueTitleValidation = Rule::unique('terms')->ignore($listingId)->where('type', $categoryType);
    }

并在验证中

'title' => [
                'required',
                'min:2',
                'max:255',
                $uniqueTitleValidation
            ],

在创建新条目时它工作正常。但是忽略我在更新时猜测的类型并抛出我已经存在错误。

这是我的数据库表

现在如您所见,我想检查列表类别。但我认为它也会检查类别类型。

注意:我使用的是 laravel 5.8

【问题讨论】:

    标签: php laravel validation eloquent


    【解决方案1】:

    试试下面的例子更干净,应该可以工作。

    
    $uniqueTitleValidation = Rule::unique('terms')
        ->where(function ($query) use($categoryType, $listingId){
                if($this->method() != 'PUT') {
                    return $query->where('type', '=', $categoryType);
                }
    
                return $query->where([
                    ['type', '=', $categoryType],
                    ['id', '<>', $listingId] // ignore this id and search for other rows
                ]);
    });
    
    

    【讨论】:

    • 这对我有用。这意味着忽略不起作用还是什么?
    • 当您放置 where 子句时,您只是将搜索范围限定为某些行,我猜忽略将不起作用。 @jayantrawat
    • 是的,我猜也是。顺便说一句,感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 2018-05-31
    • 2014-09-18
    • 1970-01-01
    • 2017-03-12
    • 2021-07-12
    相关资源
    最近更新 更多