Search code examples
phplaravellaravel-5laravel-validation

Laravel validation rule, combination of two field needs to be unique


I need the combination of menuId and foodItem name to be unique, but food item id is input value

I tried

 return [
            'foodItemId' => 'required|unique:food_items,id,' . 1 . ',menuId',
        ];

and interestingly, I have answered the similar question here, but could not make it work here!

Also, I tried

 'foodItemId' => [
             'required', 
             Rule::unique('food_items', 'id')->where(function($query) use($menu){
                 return $query->where('id', request()->input('foodItemId'))->where(function($qr) use($menu){
                     return $qr->where('menu_id', '!=', $menu);
                 });
             })
         ],

and

'foodItemId' => ['required', Rule::unique('food_items', 'id')->where(function ($query) use ($menu) {
                return $query->where('menu_id', '!=', $menu);
            })],

and

'foodItemId' => [
                'required', 'numeric', function ($attribute, $value, $fail) use ($menu) {
                    $exists =  FoodItem::where('id', request()->input('foodItemId'))
                        ->where('menu_id', $menu)
                        ->exists();

                    if (!$exists) {
                        return $fail('Your error message goes here.');
                    }
                }
            ],

Solution

  • I made a workaround for now, I hope I will get a better solution

    public function rules()
        {
            $menu = $this->menu->id;
            return [
                'foodItemId' => function ($attribute, $value, $fail) use ($menu) {
                    $foodItemName = FoodItem::find($value)->name;
                    $validationStatus = FoodItem::where('name', $foodItemName)->where('menu_id', $menu)->get()->isNotEmpty();
    
                    if ($validationStatus) {
                        $fail('This item is already in the menu.');
                    }
                },
            ];
        }