【问题标题】:Laravel array validation with custom rule使用自定义规则验证 Laravel 数组
【发布时间】:2018-10-25 03:59:53
【问题描述】:

CustomFormRequest 我有这样的事情:

public function rules(): array
{
    return [
        'events' => ['array'],
        'events.*.type' => ['required'],
        'events.*.data' => [app(SomeRule::class)],
    ];
}

SomeRule:

public function passes($attribute, $value): bool
{
    var_dump($attribute);//events.0.data
    var_dump($value);exit;
}

SomeRule::passes 中,我需要访问events.X.type(所以对于events.5.data,我需要events.5.type)。有什么想法吗?

【问题讨论】:

  • 使用辅助函数request()获取数据
  • hmm...但我需要从events.0.data 获取索引。比explode 更好的方法吗?
  • 也许检查你的验证做'events.*' => [app(SomeRule::class)], 然后$value 应该有类型和数据(也许,我不知道它是否会工作)
  • @apokryfos 我认为这将是最干净的解决方案..

标签: php laravel validation laravel-5


【解决方案1】:

正如用户在我的问题 Validating array in Laravel using custom rule with additional parameter 中评论的那样,您可以使用此代码来完成,在您的情况下,它会类似于

class SomeRule implements Rule
{
    public function passes($attribute, $value)
    {
        $index = explode('.', $attribute)[1];
        $type = request()->input("events.{$index}.type");

        return someConditional ? true : false;
    }
}

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 2017-04-11
    • 2018-02-18
    • 2014-04-22
    • 2019-02-12
    • 2016-11-22
    • 2017-12-01
    • 2017-12-06
    • 2018-05-25
    相关资源
    最近更新 更多