带有变量的 Laravel FormRequest

穆萨

知道我的验证规则需要控制器设置的变量,如何将我的验证逻辑放在 FormRequest 中?

    public function store()
    {
        $commentable = Comment::getCommentable(request('input1'), request('input1'));
        // I need this $commentable above in my validator below!

        $this->validate(request(),[
            'commentable_type' => 'required|string|alpha', // Post
            'commentable_id' => 'required|uuid|exists:' . plural_from_model($commentable) . ',' . $commentable->getKeyName(),
            'body' => 'required|string|min:1',
        ]);

        // ...
    }

这是我的实际代码:https : //i.imgur.com/3bb8rgI.png

我想整理控制器的 store() 方法,在 FormRequest 中移动 validate()。但是,如您所见,它需要 $commentable 变量,该变量由控制器检索。

我想我可以这样做,以便 FormRequest 也可以检索该变量本身,但这将是一个丑陋的重复项(因为它还会探测数据库两次......)。所以这根本不是一个好的解决方案。

任何的想法?干杯。

切贾约兹

您的 FormRequest 类可以通过prepareForValidation钩子执行预验证步骤(包括添加/修改输入数据,如下所示)

protected function prepareForValidation()
{
    $this->commentable = Comment::getCommentable($this->input('input1'), $this->input('input1'));

    $this->merge([
        'commentable_id' => $this->commentable->id,
        'commentable_type' => $this->commentable->type
    ]);
}

您也可以$this->commentable在您的rules()函数中使用

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章