繁体   English   中英

Laravel 如何验证请求类但不在方法参数中

[英]Laravel how to validate request class but not in method parameter

这是我的情况,我得到了一个使用 artisan 创建的请求类:

php artisan make:request StoreSomethingRequest

然后我把我的规则放在那里,然后我可以在我的 Controller 方法中使用它,如下所示:

public function store(StoreSomethingRequest $request)
{

}

但我需要的是,我想根据视图中的按钮分离 2 个请求逻辑(假设我的视图中有 1 个以上的提交按钮)。 所以我的控制器看起来像这样:

public function store(Request $request)
{
   if($request->submit_button === 'button1')
   {
      // I want to validate using StoreSomethingRequest here
   }
   else
   {
      // I dont want to validate anything here
   }
}

我将不胜感激任何建议/帮助。 请。 :D

您可以在规则方法内的请求类中使用类似的内容。

public function rules()
{
    $rules = [
        'common_parameter_1' => 'rule:rule',
        'common_parameter_2' => 'rule:rule',
    ];

    if($this->submit_button === 'button1')
    {
        $rules['custom_parameter_for_button_1'] = 'rule:rule';
    }
    else
    {
        $rules['custom_parameter_for_button_2'] = 'rule:rule';
    }

    return $rules;
}

在 HTML 提交按钮上添加namevalue属性。 然后查看提交的是哪一个。 例子:

<button type="submit" name="action" value="button1">Save 1</button>
<button type="submit" name="action" value="button2">Save 2</button>

然后在处理程序中:

 If (Request::input('action') === 'button1') { 
//do action 1
 } else { 
// do action 2
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM