Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

soogo's avatar
Level 1

unique rule with condition

I have a management system for employees by companies.

How can I check during the registry that there is no duplicate employee?

public function rules() { return [

    'username' => 'required|string|max:255|unique:users,username,NULL,id,company_id,' . $this->user->units->first()->company_id,
];

}

0 likes
7 replies
Cronix's avatar

Unique rule takes a max of 4 parameters. You're sending 6.

unique:table,column,except,idColumn

How can I check during the registry that there is no duplicate employee?

If that's exactly what you're trying to do, then it would just be unique:users?

soogo's avatar
Level 1

A username can be double, but only in another company (another table)

Cronix's avatar

Oh, I think it would be

'unique:users,username,' . $this->user->units->first()->company_id . ',company_id'

which would validate unique usernames except where company_id = $this->user->units->first()->company_id

tykus's avatar

You can scope the unique constraint using a Rule:

'username' => [
    'required'
    'string',
    'max' => 255,
    'username' => Rule::unique('users')->where(function ($query) {
        return $query->where('company_id', $this->user->units->first()->company_id);
    });
});
1 like
tykus's avatar

@tykus I'm using a request.

The example I gave works in a Form Request.

soogo's avatar
Level 1

What about a check against another table?

Please or to participate in this conversation.