CakePHP 3 Multiple isUnique allowing NULL duplicate

Viewed 1372

I have the following rule in my BlockedTable.php

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['date', 'time']),
        ['message' => 'unique error']);

    return $rules;
}

Up until now this has worked fine - if I try to save a new record with an already existing date and time, it prevents me from saving.

However, if my time is NULL, such as the below entry;

╔════╦══════════════╦═══════╗
║ ID ║  Date        ║ Time  ║
╠════╬══════════════╬═══════╣
║  1 ║ 22/08/1985   ║ NULL  ║
╚════╩══════════════╩═══════╝

The rule still allows me to save a new entry with the same data. So if I try to save $date = 22/08/1985 and $time = NULL it saves fine and there is a duplicate record in my database. I would of expected it to have failed due to the above rule?

Why is this happening? And how can I prevent duplicate entries on NULL values?

Thanks in advance for your help.

2 Answers

I know this is an old post but, since I had to search a lot to solve this problem, I think i should post here how I did it.

In cakePHP 3.6 you can solve this problem by changing property allowMultipleNulls to false in class isUnique.

Regards.

Related