首页 > 解决方案 > Laravel 验证 - 通过自定义规则相互验证关联数组值

问题描述

浏览有关数组验证的 Laravel 文档,我很难找到一种好的或标准的方法来验证关联数组的主体。

publish_at在下面的示例中 - 我想通过确保该日期在其父 Post 记录的日期之后来验证每个传入的评论数组是否具有有效publish_at日期。请注意,我专门寻找一种将注释上下文数组有效负载传递给自定义规则的简单方法,而不是验证此示例的显式方法(即,针对彼此验证数组值而不是验证数组值问题的通用解决方案验证所提供示例的特定方法)。

public function rules()
    {
        return [
            'data.attributes.comments' => 'present|array',
            'data.attributes.comments.*.parent_post_id' => 'required|integer|min:1',
            'data.attributes.comments.*.publish_at' => [
                'required',
                'string',
                'date',
                new CommentsPublishAtRule(
                   $this->inputAttribute('comments.*.parent_post_id')
               ),
            ],
        ];
    }

自定义规则类:

class CommentsPublishAtRule implements Rule
{
    /**
     * @var array
     */
    protected $parent_post_ids_array;

    public function __construct(array $parent_post_ids_array)
    {
        $this->parent_post_ids_array; = $parent_post_ids_array;
    }

    /**
     * This works by first grabbing the index of the current `comments` array
     * (ex: `data/attributes/comments/0/publish_at` => `0`) and then grabbing the corresponding
     * `parent_post_id` from the array of all `data/attributes/comments/n/parent_post_id`s.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // Get our index in the attribute array
        $comment_index = (int) filter_var($attribute, FILTER_SANITIZE_NUMBER_INT);
        // Grab out `parent_post_id`
        $parent_post_id = $this->parent_post_ids_array[$comment_index];

        // Check to see if the Post record exists and that the incoming `publish_at` date is valid
        return Posts::query()
            ->WherePostIdIs($parent_post_id)
            ->where('publish_at', '<=', Carbon::parse($value))
            ->exists();
    }
}

如果我不必在这里执行这些奇怪的代码,那就太好了:

// Get our index in the attribute array
$comment_index = (int) filter_var($attribute, FILTER_SANITIZE_NUMBER_INT);
// Grab out `parent_post_id`
$parent_post_id = $this->parent_post_ids_array[$comment_index];

标签: arrayslaravelvalidationlaravel-6

解决方案


推荐阅读