【问题标题】:Laravel FormRequest with variables带有变量的 Laravel FormRequest
【发布时间】:2019-09-30 08:06:42
【问题描述】:

知道我的验证规则需要控制器设置的变量,我如何将验证逻辑放入 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() 方法,将 validate() 移动到 FormRequest 中。但是,如您所见,它需要由控制器检索的 $commentable 变量。

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

有什么想法吗?干杯。

【问题讨论】:

    标签: laravel validation


    【解决方案1】:

    您的 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
        ]);
    }
    

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

    【讨论】:

    • 我可以在该 prepareForValidation() 方法中返回一个响应,以便在我的 getCommentable() 抛出异常时它会“中止”吗?我的 IDE 抱怨并不总是有“return”声明。 i.imgur.com/OTHl8lh.png
    • @13h50 我认为返回响应不会有任何作用,但您可以在最后使用return; 来帮助 IDE。 getCommentable 中的异常应该向上浮动到常规异常处理程序。
    猜你喜欢
    • 2015-04-17
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2017-09-03
    • 2016-03-05
    相关资源
    最近更新 更多