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

tjphippen's avatar

Validation: Unique IF other isset/Requre if other unique

I'd also like to validate the extension is unique only if the number is not but the first part is priority. Basically customer's phone numbers must be unique but with the ability to allow e.g. 2 people that work at the same place to use the same work number with different extensions.

I've tried various methods to no avail, including attempting to add custom validation rules.

Any help is greatly appreciated!

0 likes
6 replies
bashy's avatar

How far did you get with your custom validation rule? That's the way to go so you can do checks in the DB and allow/deny based on the results.

tjphippen's avatar

Thanks for the quick reply @bashy :)

I added a validateIf function(figured I could use it quite a bit) to my existing custom validators & got stuck at the point determining if the other field was NULL. The basic idea was something like:

    return [
        'number' => 'if:extension,null:unique,phones', 
        'extension' => 'if:number,unique,phones:required',
    ];

I could be way off though..

tjphippen's avatar

Perhaps if I first added a custom validator to determine if a field is null/empty & then call that in another custom validator.. I'll post some code shortly..

Scratch that, I'll use 'filled'

tjphippen's avatar

I've got

'number' => 'if:extension,null,unique,phones',

working with the following:

protected function validateNull($attribute, $value, $parameters)
{
    if($value == null || $value == ''){
        return true;
    }
    return false;
}

protected function validateIf($attribute, $value, $parameters)
{
    $other = Arr::get($this->data, $parameters[0]);
    $call = 'validate' . ucfirst($parameters[1]);
    if($this->$call($parameters[0], $other, null)){
        $func = 'validate' . ucfirst($parameters[2]);
        $parameters = array_slice($parameters, 3);
        return $this->$func($attribute, $value, $parameters);
    }else{
        return true;
    }
}

However getting

'extension' => 'not:number,unique,phones,required', // make extension required if number not unique

Or similar seems tricky. Any help, even just to clean this up would be great!

tjphippen's avatar

Still a bit stuck but a little explanation of the following & how best/typically it's used may help. I've seen others use similar but never in a extended validator..

$this->sometimes('number', 'unique:phones', function($blah)
{
    // ??
});

Again I'm just looking for a way to set rules for a field based on an other field passing/failing rules.

I'd think someone else would have come up with this by now, or does everyone just allow customers, user, etc to have the same phone numbers? :P

Please or to participate in this conversation.