seems it's not possible with built-in validators, how I should implement this feature in the model?

 $rules = [

            'user_id' => 'required|unique:service_details,user_id',
            'service_id'=>'required|unique:service_details,service_id'
         ];

以上将防止user_idservice_id的独立复制,这不是我的要求

it will reject

(1,2)
(1,3)

因为%1重复,但它应该被接受,因为我想要复合唯一密钥

推荐答案

Composite unique field validation is provided out-of-the-box in 5.0+. I can't speak for earlier versions.

实际上,您可以为应用唯一验证规则时指定WHERE子句.例如.

'term'  => 'unique:terms,term,NULL,id,taxonomy,category'

这条规则规定,在terms表中,term应该是唯一的,但只有在taxonomy等于"类别"的情况下.

例如,它将防止"新闻"类别被复制,但我仍然可以拥有"新闻"标签.


I don't know your schema but in your case it'd be something like this:

$user_id = Request::get('user_id', $default);
$service_id = Request::get('service_id', $default);  
// or another way of specifying the accompanying service/user ID for the where clauses

$rules = [
    'user_id' => 'unique:service_details,user_id,NULL,id,service_id,' . $service_id;
    'service_id' => 'unique:service_details,service_id,NULL,id,user_id,' . $user_id;
];

Laravel相关问答推荐

为什么Laravel在API请求时返回BadMethodCallException?

用Laravel Filament创建变形组件

如何在 Laravel 9 中获取带分页的订单列表?

如何计算具有特定 ID Laravel 的行

单个对象的Eloquent 计数是错误的

使用 App::environment() 与 app()->environment() 与 config('app.env') 之间的区别

Laravel:如何强制使用 HTTPS?

Eloquent的条件过滤器

为什么 Laravel 5 会自动更新我的日期字段?

如何使用 Eloquent Laravel 更新集合

Laravel Request::input 调用未定义的方法

CRON 作业(job) - LARAVEL - 输出

Laravel 无法创建根目录

Laravel assets资源与混合

如何运行artisan命令计划:在托管服务器上运行? (Laravel )

如何在 Laravel 中正确安装软件包?

Laravel 手动登录功能

如何让 Laravel 将 View 的Content-Type标头返回为application/javascript?

如何在不要求用户登录 Laravel 的情况下验证Electron邮件

找不到 HOME 环境 -- 扩展 `~'