Kai*_*all 5 php mysql validation laravel
我有一个表/模型,每个用户包含多个相册.有没有办法说该列title应该是唯一的,但只适用于具有相同的行user_id?
示例:http://pastebin.com/8dvM4a1T
正如您在示例中所看到的,ID为2的用户创建了2个具有相同标题的专辑.我不希望这被允许,这就是为什么我想知道是否有办法用Laravel的验证器否认这一点?
我试过这个,但那没用.
// Validator
$validator = Validator::make($input, [
'title' => 'required|min:1|max:255|unique:galleries,title,'. Auth::user() -> id .',user_id',
'description' => 'min:1|max:255'
]);
Run Code Online (Sandbox Code Playgroud)
任何帮助表示感谢,谢谢.
小智 7
你的代码应该是这样的:
'title' => 'unique:galleries,title,NULL,id,user_id,'.Auth::user() -> id.'',
Run Code Online (Sandbox Code Playgroud)
使用默认unique规则的方法不起作用,因为规则要求将列值作为第三个参数传递,因此在您的情况下,它将检查title列是否等于Auth::user()->id您不想要的值.
您可以通过将以下代码添加到类的boot方法来创建自己的自定义验证规则App\Providers\AppServiceProvider:
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
return DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
Run Code Online (Sandbox Code Playgroud)
现在你可以使用unique_custom(或者你可以任意命名)规则如下:
$validator = Validator::make($input, [
'title' => 'required|min:1|max:255|unique_custom:galleries,title,user_id,' . Auth::id(),
'description' => 'min:1|max:255'
]);
Run Code Online (Sandbox Code Playgroud)
规则要求参数如下:
galleriestitleuser_id你也可以使用,Auth::id()因为那是简短的形式Auth::user()->id.
您可以在Laravel文档中阅读有关自定义验证规则的更多信息.
| 归档时间: |
|
| 查看次数: |
4894 次 |
| 最近记录: |