使用Laravel验证来检查未删除项目中名称是否唯一 [英] Check if name is unique among non-deleted items with laravel validation
问题描述
我有一个简单的表单,该表单发布到控制器,该控制器检查某个项目的名称是否已用于特定项目.如果是,则返回错误.这是我正在使用的代码:
I have a simple form which posts to a controller which checks if a name for an item is already taken for a particular project. If it is, then it returns an error. This is the code I'm using for that:
'name' => 'required|min:1|unique:versions,name,NULL,id,project_id,'.$project->id,
我遇到的问题是,我使用软删除将其从数据库中删除,而不是硬删除,例如,"Test"只能用作一次名称,即使删除了它.
The problem I've run into is that instead of a hard delete, I'm using a soft delete to remove them from the database, meaning that, for example, 'Test' can only be used as the name once, even after it's been deleted.
在未软删除的项目中,如何使它检查该项目的唯一性?
How can I make it check that it is unique for that project among the items that are not soft deleted?
推荐答案
您可以尝试以下方法:
'name' => 'required|min:1|unique:versions,name,NULL,id,deleted_at,NULL'
这将确保versions
表中的name
将是唯一的,如果一条记录被软删除并且具有相同的名称,则该名称将不被计数,这意味着即使存在该名称,该名称也将被接受是一个具有相同名称的软删除记录.
This will make sure that the name
in the versions
table will be unique, if a record is soft deleted and has same name name then it won't be counted, means, name will be accepted even if there is a soft deleted record with the same name exists.
要在更新时忽略模型,应在name
之后传递id
代替第一个NULL
.
To ignore a model when updating, you should pass the id
after name
in the place of first NULL
.
更新:您也可以使用类似的方法添加自己的自定义规则:
Update: Also you may use something like this to add your own custom rule:
// You can declare it inside your controller method before you run validation
Validator::extend('unique_project', function($attribute, $value, $parameters)
{
// $attribute will contain field name, i.e. name
// $value will contain the value in the $attribute/name
// $parameters will be an array of arguments passed
// i.e. [0] => arg1, [1] => arg2, [2] => arg3 and so on
return true for valid and false for invalid
});
您可以这样使用它:
'name' => 'required|min:1|unique_project:arg1,arg2,arg3' // add more args if needed
这篇关于使用Laravel验证来检查未删除项目中名称是否唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!