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

AhmedNaser's avatar

Laravel unique validation rule

Hi there I have two fields one for country code and one for phone number I want to make validation to make the both fields unique together.


public function rules()
    {
        return [
            'countryCode'  => ['required', 'between:2,4'],
            'phone'    => ['required', 'digits:9', 'unique:devices,phone],
        ];
    }

I have two fields in the database one for country code, one for the phone number

I need the validation to check if the combination (country code with phone) is unique e.g +200102030 not the phone number only 0102030

0 likes
8 replies
AhmedNaser's avatar

I checked the second approach but I didn't understand what you mean when you're using where function? it could be better if you submit some explanation

Sinnbeck's avatar

Give this a shot

$rules = [
            'phone' => [Rule::unique('devices')->where(function ($query) use ($request) {
                return $query->where('phone', $request->input('phone'))->where('countryCode', $request->input('countryCode'));
            }),'required', 'digits:9']
];
Tray2's avatar
Tray2
Best Answer
Level 73

I have done this in my app Where the combination between the first and the last name of an author must be unique.

'first_name' => 'required|unique:authors,first_name,' . null . ',id,last_name,'. $request->last_name

It should be quite easy for you to change the name of the fields to suit your needs.

1 like
jeevamugunthan's avatar

@ahmednaser you need to use validator

use Illuminate\Support\Facades\Validator;

use App\users;

$validator = Validator::make($request->all(), [

        'phone' => ['required', 'string', 'email', 'max:255', 'unique:users'],  //users is table name and phone is column name//
      ]);
omidrayaneh's avatar

use this code :


    $validator= $request->validate([
            'title' => 'required|min:3|unique:categories,title,'.$category->id,
            'description' => 'required',
        ]);

Please or to participate in this conversation.