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

mshshuvooo's avatar

How can I use whereHas() method in Rule::unique() for Multi Column Unique Validation

Can I use the whereHas method in Rule::unique() ? There is no column here for cows, the data of cows are coming from the pivot table by the ManyToMany relationship. Please help me.

I want something like that:


public function rules(): array
    {
        return [
            'vaccination_date' => [
                'required', 'date', 'before:tomorrow',
                Rule::unique('vaccines', 'vaccination_date')
                ->where(function ($query) {
                    $query->where('vaccination_date', $this->input('vaccination_date'))
                    ->where('next_vaccination_date', $this->input('next_vaccination_date'))
                    ->where('vaccine_type', $this->input('vaccine_type'))
                    ->where('dose', $this->input('dose'))
                    ->whereHas('cows', function($query)  {
                        $query->whereIn('id', [1,2]);
                    })->get();
                }),],

            'next_vaccination_date' => ['required', 'date', 'after:vaccination_date'],

            'vaccine_type' => [
                'required',
                'string',
                new Enum(VaccineTypeEnum::class)
            ],
            'dose' => [
                'required',
                'string',
                new Enum(VaccineDoseEnum::class)
            ],
            'cows' => ['required', 'array', 'min:1', Rule::exists('cows', 'id')],

        ];
    }
1 like
0 replies

Please or to participate in this conversation.