Laravel 验证:唯一,当名称相同,但其他字段不同时
Laravel validation: unique, when name is equal, but other field is different
标签可以具有相同的名称,但它们的值 modul_id
不同。
目前我使用这段代码:
$tag = Tag::firstOrNew([
'name' => $request->get('name'),
'modul_id' => Modul::where('short', $modul_short)->first()->id
]);
if(!$tag->id) {
$tag->save(); //this is a new entry
} else {
//record was allready there
}
是否可以为 "you can have the same name, but then you need a different modul_id" 制定验证规则?
您可以使用 Laravel 验证器和独特的验证规则:
$module_id = $request->get('module_id');
$rules = [
'name' => 'unique:tags,name,NULL,id,modul_id,'.$module_id
]
这假设 module_id 随请求一起提供(或者在验证之前以其他方式获取。
该示例表示,对 'name' 列上的 table 'tags' 执行唯一检查,但此检查仅对 运行匹配给定的 $module_id。
有关更多信息,您可以查看 Laravel Docs - Unique Validation rule
标签可以具有相同的名称,但它们的值 modul_id
不同。
目前我使用这段代码:
$tag = Tag::firstOrNew([
'name' => $request->get('name'),
'modul_id' => Modul::where('short', $modul_short)->first()->id
]);
if(!$tag->id) {
$tag->save(); //this is a new entry
} else {
//record was allready there
}
是否可以为 "you can have the same name, but then you need a different modul_id" 制定验证规则?
您可以使用 Laravel 验证器和独特的验证规则:
$module_id = $request->get('module_id');
$rules = [
'name' => 'unique:tags,name,NULL,id,modul_id,'.$module_id
]
这假设 module_id 随请求一起提供(或者在验证之前以其他方式获取。
该示例表示,对 'name' 列上的 table 'tags' 执行唯一检查,但此检查仅对 运行匹配给定的 $module_id。
有关更多信息,您可以查看 Laravel Docs - Unique Validation rule