Laravel 验证规则,两个字段的组合需要唯一

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

我需要menuId和foodItem名称的组合是唯一的,但是food item id是输入值

我试过了

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

有趣的是,我已经回答了类似的问题 ,但无法在此处使用!

另外,我试过了

 '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);
                 });
             })
         ],

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

'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.');
                    }
                }
            ],

把不等于!=改成等于=:

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

我暂时做了一个解决方案,希望我能得到更好的解决方案

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.');
                }
            },
        ];
    }