首页 > 解决方案 > 具有两个字段的数组上的 Laravel 验证存在于数据库行上

问题描述

我有一个输入数组,每个项目包含 2 个字段:

"items" :[
    {
        "product_id" : 23232,
        "product_offer_id" : 3434
    },
    {
        "product_id" : 4545,
        "product_offer_id" : 67676
    }

]

我想验证product_offer_idand是否product_id存在于products表中。当前规则:

$rules = [
    'items' => 'required',
    'items.*.product_id' => 'required|exists:products,id',
    'items.*.product_offer_id' => 'required|exists:product_offers,id',
    'items.*.quantity' => 'required|numeric',
];

没有数组我这样做:

$product_id = \Input::get('product_id');

$rules = [
    'product_id' => 'required|exists:products,id',
    'product_offer_id' => [
        'required',
        \Illuminate\Validation\Rule::exists('product_offers','id')
        ->where(function ($query) use ($product_id) {
            $query->where('product_id', $product_id);
        })
     ]
];

标签: phplaravellaravel-5

解决方案


您将需要根据您使用 Laravel 类验证器编写的规则运行包含您的项目的输入数组。

Validator::make($yourInputArray, $rules)->validate();


推荐阅读