I have the following database table structure for an agents
table
+--------------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| first_name | varchar(255) | NO | | NULL | |
| phone | varchar(255) | NO | MUL | NULL | |
| active | tinyint(1) | YES | | NULL | |
+--------------------------+---------------------+------+-----+---------+----------------+
the fields phone
and active
is having a 2 column unique constraint, meaning only one phone
should be in the active state at once. the column active
is a nullable boolean, because if I put 0
for the falsy value then the 2 columns unique constraint will fail if there are two inactive phone
numbers (since null != null it is working fine on the database level when I manually insert it in database). I hope I am clear here.
The Problem
I am trying to set up the validation rules for this feature. So while creating an agent if there is any active
phone numbers the validation should fail, otherwise, the record should be inserted.
here is my validation rule
$request->validate([
'first_name'=> 'required',
'active' => 'required',
'phone' => [
'required',
Rule::unique('delivery_agents')->using(function ($query) use ($request) {
$query->where('phone', $request->phone)
->where('active', $request->active ? $request->active : null); // explicitly checking against null value or true not 0
})
],
]);
But the validation rule fails when there is one inactive phone number (ie: phone
number with active = null
)
I believe the reason is that the validation rule checks for phone number with active = null
and since there is one record like that it throws the validation failed exception. How do I mitigate this.
Found a post here but again it's the same thing I have posted in the question.
Using Laravel 6, and Mysql 8