Home > Blockchain >  Laravel unique validation more than one with rule
Laravel unique validation more than one with rule

Time:10-11

I have a problem with unique validate on Laravel 9

I want to validate with data not same category_id and not same month, also year

For example i have data:

{
  category_id: 1
  month: 2
  year: 2022
}

if i input with

{
  category_id: 1
  month: 3
  year: 2022
}

My expectation the data is successfully saved, and if data like this:, its cant saved.

{
  category_id: 1
  month: 3
  year: 2022
}

Because of same category_id and month and year.

My Code:

$this->validate($request, [
    'category_id' => [
        'required',
        Rule::unique('categories')
            ->where('month', '!=', $request->month)
            ->where('year', '!=', $request->year),
        ],
]);

How to write this validation on Laravel 9? Thanks before.

CodePudding user response:

Don't use '!=' sign.

Rule::unique('categories')
    ->where('month', $request->month)
    ->where('year', $request->year)
  • Related