Laravel:如何在表单请求验证中使用忽略规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47646900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:02:48  来源:igfitidea点击:

Laravel: How to use the ignore rule in Form Request Validation

phplaravelvalidationlaravel-validation

提问by Kim Prince

Laravel has a 'unique' rule with an 'except' clause. From the validation documentation, it takes this form:

Laravel 有一个带有“except”子句的“unique”规则。从验证文档中,它采用以下形式:

unique:table,column,except,idColumn

My application has a 'shop' entity. When the user updates the shop's profile, I have a Form Request, with a validation rule configured as follows:

我的应用程序有一个“商店”实体。当用户更新商店的个人资料时,我有一个表单请求,其验证规则配置如下:

public function rules()
{
    return [
        'shop.name' => 'required|string|max:100|unique:shops,name,except,id',
    ];
}

(The primary key on my shopstable is id).

(我shops桌子上的主键是id)。

The problem is that Laravel does not take any notice of the 'except' clause. This makes sense (sort of) since the shop ID is not being injected into the Form Request. I can inject idas just another form value, but that doesn't seem to work.

问题是 Laravel 没有注意到 'except' 子句。这是有道理的(有点)因为商店 ID 没有被注入到表单请求中。我可以id作为另一种形式值注入,但这似乎不起作用。

How can I get this rule working in a Form Request?

如何在表单请求中使用此规则?

回答by Cy Rossignol

To use the exceptclause to the uniquerule, we need to provide the valueof the field on the record that we want the rule to ignore directly in the rule itself.

要将except子句用于unique规则,我们需要直接在规则本身中提供我们希望规则忽略的记录上字段的

So, if we want a unique namefield for every record exceptfor on the record that the request updates, we need to add the value of the ID field to ignore:

所以,如果我们希望除了请求更新的name记录之外的每条记录都有一个唯一的字段,我们需要添加 ID 字段的值以忽略:

class UpdateShopRequest extends FormRequest
{
    ...
    public function rules() 
    {
        return [
            'shop.name' => 'unique:shops,name,' . $this->shop['id'],
        ];
    }
}

As shown, this rule will cause validation to fail if any row contains the same shop name unlessthe row's idmatches $this->shop['id']. This example assumes that our form contains an array input field for the record's ID attribute because the question is performing validation on an array input:

如图所示,如果任何行包含相同的商店名称,除非该行的id匹配项,否则此规则将导致验证失败$this->shop['id']。此示例假设我们的表单包含记录 ID 属性的数组输入字段,因为问题是对数组输入执行验证:

<input type="hidden" name="shop[id]" value="{{ $shop->id }}">

...which lets us fetch the value within the request like we can with any other request. More typically, we pass the record ID as a route parameter, which we can retrieve using the request's route()method:

...这让我们可以像处理任何其他请求一样获取请求中的值。更典型的是,我们将记录 ID 作为路由参数传递,我们可以使用请求的route()方法检索它:

$shopId = $this->route('id');

...which works if we have a route defined similarly to:

...如果我们定义的路由类似于:

Route::post('shops/{id}', ...);

The fourth parameter to the uniquevalidation rule lets us specify which column the exceptclause applies to, and defaults to id, so we can leave it off if we're just comparing the record's ID.

unique验证规则的第四个参数让我们指定except子句适用于哪一列,默认为id,所以如果我们只是比较记录的 ID,我们可以不使用它。

The rule looks a bit clumsy when we just concatenate the column value, especially for a field with a lot of other rules. Since version 5.3, Laravel provides a more elegant syntax to create a uniquerule with an exceptclause:

当我们只是连接列值时,规则看起来有点笨拙,尤其是对于具有许多其他规则的字段。从 5.3 版本开始,Laravel 提供了一种更优雅的语法来创建unique带有except子句的规则:

use Illuminate\Validation\Rule;
...
return [
    'shop.name' => [ 
        'required', 
        'string', 
        'max:100', 
        Rule::unique('shops', 'name')->ignore($shopId, 'optional_column'), 
    ],
];

回答by Romain 'Maz' BILLtheitroad

This example assumes that our form contains an array input field for the record's ID attribute because the question is performing validation on an array input: <input type="hidden" name="shop[id]" value="{{ $shop->id }}">

此示例假设我们的表单包含记录 ID 属性的数组输入字段,因为问题是对数组输入执行验证: <input type="hidden" name="shop[id]" value="{{ $shop->id }}">

Laravel 5.8: I've tried you solution right now, without adding the input, it's working well. Because Laravel pass the Shop object into request (shown with dd() into rules() )

Laravel 5.8:我现在已经尝试过你的解决方案,没有添加 input,它运行良好。因为 Laravel 将 Shop 对象传递给请求(显示为 dd() 到 rules() )

Just:

只是:

`public function rules()
{
    return [
        'name' => 'unique:shops,name,'.$this->shop->id
    ];
}`