Larave validation: If added language already exists in this group_id then don't add

Viewed 23

I have got an table with 2 foreign keys in it: language_id and group_id.

Every new post i make gets a new group_id, if i add a translation to a post it gets the same group_id as the selected post so no new group_id for that one.

So what i want to achieve is a validation rule that does this:

  • If i want to add a translation with a other language_id it has to check if the language_id already exists but only in the same group_id.

my table (SupportGuideTranslation):

id / title / body / keywords / language_id / group_id / date

1 Answers

Use rule exists and add your groupId as a special condition.

[
    'language_id' => Rule::exists('SupportGuideTranslation', 'language_id')
        ->where(function ($query) use ($groupId) {
             return $query->where('group_id', $groupId);
        }),
]
Related