使用 Laravel 验证检查名称在未删除的项目中是否唯一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23374995/
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
Check if name is unique among non-deleted items with laravel validation
提问by Samsquanch
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,
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.
我遇到的问题是,我使用软删除将它们从数据库中删除,而不是硬删除,这意味着,例如,“Test”只能用作名称一次,即使在它之后被删除。
How can I make it check that it is unique for that project among the items that are not soft deleted?
如何在未软删除的项目中检查该项目是否唯一?
回答by The Alpha
You may try this:
你可以试试这个:
'name' => 'required|min:1|unique:versions,name,NULL,id,deleted_at,NULL'
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
在versions
表将是独一无二的,如果一个记录被软删除,并且具有相同的名称命名,那么它不会被计算在内,手段,名将即使有软删除的记录具有相同名称的被接受存在。
To ignore a model when updating, you should pass the id
after name
in the place of first NULL
.
要在更新时忽略模型,您应该通过id
aftername
代替 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
});
You may use it like this:
你可以这样使用它:
'name' => 'required|min:1|unique_project:arg1,arg2,arg3' // add more args if needed
回答by mp035
I know this question is old, but I stumbled across this when looking for a solution to a similar problem. You don't need custom validation code.
我知道这个问题很老,但我在寻找类似问题的解决方案时偶然发现了这个问题。您不需要自定义验证代码。
I have a database of ledger codes in which the 'name' and 'short_name' must be unique for each user (user_id). I have soft deletes enabled, so they should only be unique among non-deleted rows for a given user.
我有一个分类帐代码数据库,其中“名称”和“short_name”对于每个用户(user_id)必须是唯一的。我启用了软删除,因此它们应该只在给定用户的未删除行中是唯一的。
This is my function which returns the validation strings:
这是我返回验证字符串的函数:
protected function validation_data($user_id, $update_id = "NULL") {
return [
'name' => "required|max:255|unique:ledger_codes,name,$update_id,id,deleted_at,NULL,user_id,$user_id",
'short_name' => "max:255|min:3|unique:ledger_codes,short_name,$update_id,id,deleted_at,NULL,user_id,$user_id",
'description' => 'max:255',
];
}
For any one wondering about the argument string syntax for the unique validator, it is as follows:
对于任何想知道唯一验证器的参数字符串语法的人,如下所示:
- arg 0: The table name in the database
- arg 1: the field name in which the value is unique
- arg 2: a single id which is to be ignored (set to uppercase NULL if you are not using it.)
- arg 3: the field in which the single id resides. It defaults to 'id' so if you are not using it, and you have more arguments, use the string 'id'.
- arg 4/5: a field name/value pair for a where clause (
where('deleted_at',null)
in my example.) - arg 6/7: another field name/value pair (
where('user_id', $user_id)
in my example). - arg 8/9: another field name value pair
- arg 10/11: another.......
... and so on.
- arg 0:数据库中的表名
- arg 1:值唯一的字段名
- arg 2:将被忽略的单个 id(如果您不使用它,则设置为大写 NULL。)
- arg 3:单个 id 所在的字段。它默认为“id”,因此如果您不使用它,并且您有更多参数,请使用字符串“id”。
- arg 4/5:where 子句的字段名称/值对(
where('deleted_at',null)
在我的示例中。) - arg 6/7:另一个字段名称/值对(
where('user_id', $user_id)
在我的示例中)。 - arg 8/9:另一个字段名称值对
- arg 10/11:另一个…………
等等。
The value fields in field name/value pairs can be either a value to match, NULL, or NOT_NULL.
字段名称/值对中的值字段可以是要匹配的值、NULL 或 NOT_NULL。
回答by Scofield
If someone is looking for solution using Rule
class.
如果有人正在使用Rule
类寻找解决方案。
use Illuminate\Validation\Rule;
class UpdateArticleRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$data = $this->request->all();
return [
'slug' => [
'required',
Rule::unique('articles')->ignore($data['id'])->whereNull('deleted_at')
]
];
}
}
Basically, we just ignoring rows which deleted_at
fields are not null
.
基本上,我们只是忽略deleted_at
字段不是的行null
。
Here are the methods which you can use along with ignore
function: https://laravel.com/api/5.7/Illuminate/Validation/Rules/DatabaseRule.html
以下是您可以与ignore
函数一起使用的方法:https: //laravel.com/api/5.7/Illuminate/Validation/Rules/DatabaseRule.html
回答by Matías Haurigot
On Create Method:
关于创建方法:
public function store(Request $request)
{
$request->validate([
'name'=>'required|unique:form_types,name,NULL,id,deleted_at,NULL',
]);
// Write your code here
}
On Update Method:
关于更新方法:
public function update(Request $request, $id)
{
$request->validate([
'name'=>'required|unique:form_types,name,'.$id.',id,deleted_at,NULL',
]);
// Write Code here
}
回答by Aamir Anwar
For add record
用于添加记录
'name' => [
'required',
'string',
'min:3',
Rule::unique('products')->where(function ($query) {
return $query->where('store_id', Auth::user()->store_id);
})->whereNull('deleted_at'),
],
For edit that record
用于编辑该记录
'name' => [
'required',
'string',
'min:3',
Rule::unique('products')->where(function ($query) {
return $query->where('store_id', Auth::user()->store_id);
})->ignore($request->id, 'id')->whereNull('deleted_at'),
],