如何在laravel验证上强制数据更新自定义唯一

时间:2018-05-19 08:12:45

标签: laravel-5.4 laravel-validation

我是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'
        ]
    );
}

1 个答案:

答案 0 :(得分:0)

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

编辑: 如果标题未更改,则无法更新记录,则需要向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;
});