因此,用户需要update
个产品和用户的产品必须具有唯一的名称,我不希望用户收到错误消息Product with same name already exists
如何调整Laravel的unique
验证器来执行此操作
$sql = "SELECT `id` FROM `products` WHERE `name` = '$value' AND user_id != '$user_id' AND id != '$id' ";
这将确保如果用户决定保持产品名称不变,则product name with same already exists
不会出现任何错误消息,只要它属于同一用户并且产品ID保持不变
我在FormRequest rules()
中尝试了这个 $id = $this->route('id');
$user_id = $this->user()->id;
return [
'name'=>"unique:product,name,user_id,$user_id,id,$id"
];
答案 0 :(得分:1)
您应该添加自定义验证,这是我的解决方案:
,像这样更改启动功能
public function boot()
{
Illuminate\Support\Facades\Validator\Validator::resolver(function($translator, $data, $rules, $messages) {
return new \App\CustomValidation($translator, $data, $rules, $messages);
});
}
将CustomValidation.php添加到app文件夹,代码如下
use Illuminate\Validation\Validator;
class CustomValidation extends Validator
{
public function validateCustomUnique($attribute, $value, $parameters)
{
//$attribute is the filed name which you want validate
//$value is the value of that filed
//$parameters is an array which you can pass extra paramter form validation
}
}
return [
'name'=>"custom_unique:$paramter1,$params2,$paramter4"//these paramters will pass to validateCustomUnique function
];