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

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

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

unique:table,column,except,idColumn

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

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

(我的 shops table 上的主键是 id)。

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

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

要使用 unique ruleexcept 子句,我们需要提供记录中字段的 ,我们希望规则直接在规则中忽略 .

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

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

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

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

...这让我们可以像处理任何其他请求一样获取请求中的值。

但是,大多数表单不包含数组,因此——在其他情况下——验证规则可能会直接引用输入字段(没有嵌套标识符):

'name' => 'unique:shops,name,' . $this->id,

更典型的是,我们将记录 ID 作为路由参数传递,我们可以使用请求的 route() 方法检索它:

'name' => 'unique:shops,name,' . $this->route('id'),

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

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

unique 验证规则的第四个参数让我们指定 except 子句适用于哪一列,默认为 id,因此如果我们可以将其关闭'只是比较记录的 ID。

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

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

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

Laravel 5.8:我现在已经尝试了您的解决方案,没有添加输入,效果很好。因为 Laravel 将 Shop 对象传递到请求中(显示为 dd() 到 rules() )

刚刚:

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

for laravel 8 使用 $this->get('id') 排除当前记录以供品尝

use Illuminate\Foundation\Http\FormRequest;

class Update extends FormRequest
{
  public function rules()
  {
    return [
        'name' => ['required', 'string', 'unique:shops,slug,'. $this->get('id')],
    ];
  }
}