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,
];
}
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?
A username can be double, but only in another company (another table)
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
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);
});
});
@tykus I'm using a request.
The example I gave works in a Form Request.
What about a check against another table?
Please or to participate in this conversation.