arrays - 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];
解决方案
推荐阅读
- module - 如何在编译时以程序方式构造属性的值?
- javascript - 当我尝试使用 RDB 时发生 Firebase 数据库 URL 错误
- python - 无法在仅 tensorflow CPU 安装上加载动态库“cudart64_101.dll”
- ios - SwiftUI-如何在 swfitUI 中为某个时间间隔制作动画图像?
- ubuntu - Tomcat 9 - Linux Ubuntu 18.04 中的位置
- r - R package psych 组合后两个均值在一个变量中
- python-3.x - 如何使用 matplotib.dates.date2num 获取条形图中条形的宽度?
- mysql - 使用连接的 NULL 或 0 组的 COUNT
- reactjs - 在 React 中查找 td 的值
- c++ - doxygen:在类文档下的部分中包含方便别名的文档