0

i am new to Laravel i need some help in validation. i have two fields one is for country code and other is for phone number and they are being stored separately in respective column in database. i want to validate phone number as unique what i want is get phone number (1234567) country_Code(+12) join them as one like (+121234567) and then validate(unique) against db columns country_Code(+12) + phone(1234567). how can i achieve this?

here is my validation rules method for custom form request

public function rules()
{
    return [
        'first_name' => 'required|string',
        'last_name' => 'required|string',
        'email' => ['required', Rule::unique('clients')->ignore($this->client)],
        'country_code' => 'required',
        'phone' => ['required',Rule::unique('clients')->ignore($this->client)],
        'receive_video_lessons' => 'required|boolean'
    ];
}
Mudassar
  • 3
  • 3

1 Answers1

0

You could use a custom rule. Try something like this:

public function rules()
    {
        return [
            'first_name' => ['required', 'string'],
            'last_name' => ['required', 'string'],
            'email' => ['required', Rule::unique('clients')->ignore($this->client)],
            'country_code' => ['required'],
            'phone' => ['required', new IsValidPhoneNumber($this->country_code, $this->client)],
            'receive_video_lessons' => 'required|boolean'
        ];
    }

Then in your custom validation rule:

class IsValidPhoneNumber implements Rule
{
    protected $countryCode;
    protected $clientId;

    public function __construct($countryCode, $clientId)
    {
        $this->countryCode = $countryCode;
        $this->clientId = $clientId;
    }

    public function passes($attribute, $value)
    {
        return ! Client::where('country_code', $this->countryCode)
            ->where('phone', $value)
            ->where('client_id', '!=', $this->clientId)
            ->exists();
    }

    public function message()
    {
        return 'This :attribute is not valid.';
    }
}

You might have to massage it to work but you get the idea.

PW_Parsons
  • 1,173
  • 2
  • 12
  • 19