Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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'
         ];

above will prevent duplicacy of user_id and service_id independently which is not my requirement

it will reject

(1,2)
(1,3)

because 1 is duplicate but it should be accepted as i want composite unique key

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
495 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

You can essentially specify a where clause for when your unique validation rule applies. E.g.

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

This rule says that term should be unique on the terms table but only where the taxonomy is equal to "category".

For example, it will prevent a "news" category being duplicated but I can still have a "news" tag.


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;
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...