Monday, March 6, 2017

Laravel 5.3 - Complex unique rule with formatting check

So as part of the project I'm on, we're allowing people to add 'followers' to be notified on updates to a customer's record. These followers may have multiple e-mail addresses and phone numbers attached to them, using a polymorphic table structure for e-mail addresses (email_addresses.email) and phone numbers (phones.number). Phone numbers are stored strictly as 10 digits.

I'm trying to add validation rules so that an error is thrown if an e-mail address or phone number is already in use with another follower on this specific record. I would do this at the processing stage when the user's input is scrubbed but I don't know how to add an error message to the error bag and trip the validation as a failure.

Existing rules:

'emails' => 'array',
'emails.*' => ['email'],
'phones' => 'array',
// anything with 10 digits, since everything else is being stripped off
'phones.*' => ['string', 'regex:/(?=(?:.*[0-9]){10})/'],

I've looked at Rule::exists() and found there is nothing to check for the opposite, and I looked at Rule::unique() but this doesn't seem to consider this level of complexity. I could potentially grab all the existing e-mails and phone numbers to use with not_in but I'm trying not to format the data at this level.

How should I implement this?



via Dissident Rage

Advertisement