【问题标题】:How to force data update on laravel validation custom unique如何在 laravel 验证自定义唯一性上强制数据更新
【发布时间】:2018-10-29 14:20:25
【问题描述】:

我是 laravel 的新手。我有一个带有 menu_id 和标题的表,当具有相同的 menu_id 时,我试图使这个标题字段唯一。我找到了解决方案here

但是更新时遇到问题。有人可以帮忙吗? 我的代码

Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
    // Get the parameters passed to the rule
    list($table, $field, $field2, $field2Value) = $parameters;

    // Check the table and return true only if there are no entries matching
    // both the first field name and the user input value as well as
    // the second field name and the second field value
    return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});

public function updateSubmenu( Request $request) {
    $this->validate( $request, [
            'menu_id' => 'required',
            'title' => 'required|unique_custom:posts,title,menu_id,'.$request->menu_id,
            'order_by' => 'required|integer',
            'description' => 'required'
        ],
        [
            'title.unique_custom' => 'This title already token'
        ]
    );
}

【问题讨论】:

    标签: laravel-5.4 laravel-validation


    【解决方案1】:

    你能解释一下你在更新时遇到了什么问题吗?有什么例外?

    编辑: 如果 title 没有变化就无法更新记录,需要在 Validator 中添加一个条件:

    Validator::extend('unique_custom', function ($attribute, $value, $parameters)
    {
        // Get the parameters passed to the rule
        list($table, $field, $field2, $field2Value) = $parameters;
    
        // If old value not changed, don't check its unique.
        $current = \DB::table($table)->where('title')->first();
        if( $current->{$field} == $value) {
            return true;
        }
        return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
    });
    

    【讨论】:

    • 问题是在标题不变的情况下,我无法更新其他列。
    猜你喜欢
    • 2021-11-30
    • 2019-12-10
    • 2014-08-20
    • 2021-01-23
    • 2014-12-16
    • 2016-09-26
    • 2021-04-16
    • 2014-06-28
    • 1970-01-01
    相关资源
    最近更新 更多