You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel自定义规则如何向CheckForStockAvailability传递数组内的locationId

实现步骤

1. 先修改自定义规则类,增加构造参数接收locationId

打开你的CheckForStockAvailability规则类,添加构造方法存储传入的locationId:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\ValidationRule;

class CheckForStockAvailability implements ValidationRule
{
    // 存储传入的locationId
    protected string|int $locationId;

    // 构造方法接收参数
    public function __construct(string|int $locationId)
    {
        $this->locationId = $locationId;
    }

    public function validate(string $attribute, mixed $value, \Closure $fail): void
    {
        // 这里就可以直接用$this->locationId拿到对应值,和当前校验的productId($value)做库存校验逻辑
        // 你的原有校验逻辑
    }

    // 老版本Laravel用passes方法的写法同理
    // public function passes($attribute, $value)
    // {
    //     // $this->locationId 直接调用即可
    // }
}

2. 调整FormRequest的rules方法,传入locationId

在FormRequest中直接提前取出reservedProducts.locationId的值,实例化规则的时候传入即可,全程只传递你需要的单个字段,不会暴露整个请求参数:

public function rules()
{
    // 仅取出你需要的locationId值
    $locationId = $this->input('reservedProducts.locationId');

    return [
        'reservedProducts' => ['bail', 'array'],
        // 可选:先给locationId加校验,确保值合法再传入自定义规则
        'reservedProducts.locationId' => ['required', 'integer', 'exists:locations,id'],
        'reservedProducts.*.productId' => ['required', new CheckForStockAvailability($locationId)],
    ];
}

如果你的Laravel版本比较新,也可以直接在自定义规则内部通过request()助手单独获取locationId,不需要传参,但上面的传参方式更清晰,完全符合你「仅传递单个属性」的要求。

内容的提问来源于stack exchange,提问作者Mike Ross

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:36:03