Laravel 5.5 - 同时验证多个表单请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48370879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:16:49  来源:igfitidea点击:

Laravel 5.5 - Validate Multiple Form Request - at the same time

phplaravelvalidationlaravel-5.5request-validation

提问by ab.in

The question is already asked herefor a previous version of laravel and not yet answered.

此处已针对先前版本的 laravel提出该问题,但尚未回答。

I have a html formwhich is validated using three different Form Request Validations. I am able to do this. But, the problem is, the form validations take place one by one. Not at the same time.

我有一个html form使用三个不同的Form Request Validations. 我有能力做到这一点。但是,问题是,表单验证是一一进行的。不是同时。

If the first form request throws a validation error the form is returned to the viewso rest of the two forms doesn't evaluated, hence a proper validation error can't be displayed to the user.

如果第一个表单请求引发验证错误,则该表单将返回给view其他两个表单,因此不会评估其余的表单,因此无法向用户显示正确的验证错误。

What I want is : validate the form with the three form validation requests rulesat the same time.

我要的是:验证表单与三个表单验证请求rules在同一时间

Controller:

控制器:

public function store(TransportationRequest $request1, PurchaseRequest $request2, SaleRequest $request3)
    {
        //do actions here
    }

I have tried with inheriting the form requests one by one but could not be succeeded.

我试过一一继承表单请求,但没有成功。

Edit :

编辑 :

To be more specific to my question:

更具体地说明我的问题:

I do have three seperate forms for purchase, transporataionand salewhich are individually valuated using PurchaseRequest, TransportationRequestand SaleRequestfor individual operations.

我有三个独立的形式purchasetransporataion以及sale其使用单独计价PurchaseRequestTransportationRequest并且SaleRequest对单个操作。

But there is a special casewhere a single form handles a purchase, transporataionand a sale. I want to validate the form using combining the three form request rulesbecause I didn't want to write the same validation rules again.

但是有一个特殊情况,在一个单一的形式处理一个purchasetransporataion和一个sale我想使用组合三个表单请求规则来验证表单,因为我不想再次编写相同的验证规则。

This

这个

Note : The fields in the seperate forms and combined form are same.

注意:单独表格和组合表格中的字段相同。

Thanks..

谢谢..

回答by sam

A FormRequest throws an Illuminate\Validation\ValidationExceptionException when validation fails which has a redirectTomethod, and from there the Exception Handlerperforms the redirect.

Illuminate\Validation\ValidationException当具有redirectTo方法的验证失败时,FormRequest 抛出异常,然后异常Handler执行重定向

You can achieve your desired behaviour by running your Form Requests manually in your controller within a try/catch block which captures the errors and combines the error bags before redirecting, or if it's essential that you run them by Laravel injecting them into your controller then you would need to add your own exception handler which captures all of the errors, combines them and then redirects after the final Form Request has ran.

您可以通过在 try/catch 块中的控制器中手动运行表单请求来实现您想要的行为,该块捕获错误并在重定向之前组合错误包,或者如果您必须通过 Laravel 将它们注入控制器来运行它们,那么您需要添加您自己的异常处理程序来捕获所有错误,将它们组合起来,然后在最终的表单请求运行后重定向。

However, it's worth noting, both of those approaches aren't great: they're cumbersome and are going to cause you more problems than they solve. You should try to adhere to the Laravel way of doing things as best possible if you'd like to write a maintainable application.

但是,值得注意的是,这两种方法都不是很好:它们很麻烦,并且会给您带来比它们解决的更多的问题。如果您想编写一个可维护的应用程序,您应该尽量坚持 Laravel 的做事方式。

A Form Request exists to validate a form, therefore, each Form should have one Form Request, if you wish to compose a Form Request from different sets of rules then that should be done within the Form Request, e.g:

存在表单请求以验证表单,因此,每个表单应该有一个表单请求,如果您希望从不同的规则集组成表单请求,那么应该在表单请求中完成,例如:

  1. Define your Form Request for your form php artisan make:request StoreMultipleForm
  2. From the rulesmethod on StoreMultipleFormfetch the rulesfor each of the other Form Requests and then return them together, e.g:

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $formRequests = [
          TransportationRequest::class,
          PurchaseRequest::class,
          SaleRequest::class
        ];
    
        $rules = [];
    
        foreach ($formRequests as $source) {
          $rules = array_merge(
            $rules,
            (new $source)->rules()
          );
        }
    
        return $rules;
    }
    
  3. Use the new composed Form Request in your controller, e.g:

    public function store(StoreMultipleForm $request)
    {
        // Do actions here.
    }
    
  1. 为您的表单定义表单请求 php artisan make:request StoreMultipleForm
  2. rules方法StoreMultipleFormrules为每个其他表单请求获取 ,然后将它们一起返回,例如:

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $formRequests = [
          TransportationRequest::class,
          PurchaseRequest::class,
          SaleRequest::class
        ];
    
        $rules = [];
    
        foreach ($formRequests as $source) {
          $rules = array_merge(
            $rules,
            (new $source)->rules()
          );
        }
    
        return $rules;
    }
    
  3. 在您的控制器中使用新的组合表单请求,例如:

    public function store(StoreMultipleForm $request)
    {
        // Do actions here.
    }
    

The advantages of this method are that it's self-contained, it adheres to the one form one Form Requestexpectation, it doesn't require changes to the Form Requests you're combining and if you need to add additional rules unique to this form you can do so without creating anotherForm Request.

这种方法的优点是它是自包含的,它遵循一个表单请求的期望,不需要更改您正在组合的表单请求,如果您需要添加此表单独有的其他规则,您可以在不创建另一个表单请求的情况下这样做。

回答by Jonathon

If I understand correctly, you have 3 forms, each with their own form requests to deal with their respective validation. You also have another form which combines those 3 forms somewhere else and you don't want to repeat yourself by rewriting those validation rules.

如果我理解正确,您有 3 个表单,每个表单都有自己的表单请求来处理各自的验证。您还有另一个表单,它在其他地方组合了这 3 个表单,并且您不想通过重写这些验证规则来重复自己。

In which case, I would still suggest going with a single form request, but try to combine the rules of each of those individual requests. For example, you use static methods to define your rules on the 3 individual form requests and have each individual request call its own static method to grab them:

在这种情况下,我仍然建议使用单个表单请求,但尝试结合每个单独请求的规则。例如,您使用静态方法在 3 个单独的表单请求上定义规则,并让每个单独的请求调用自己的静态方法来获取它们:

class TransportationRequest extends FormRequest
{
    public static function getRules()
    {
        return []; // Return rules for this request
    }

    public function rules()
    {
        return static::getRules();
    }
}

class PurchaseRequest extends FormRequest
{
    public static function getRules()
    {
        return []; // Return rules for this request
    }

    public function rules()
    {
        return static::getRules();
    }
}

class SaleRequest extends FormRequest
{
    public static function getRules()
    {
        return []; // Return rules for this request
    }

    public function rules()
    {
        return static::getRules();
    }
}

And then have your combined requestmerge all three sets:

然后让您的合并请求合并所有三组:

class CombinedRequest extends FormRequest
{
    public function rules()
    {
        return array_merge(
            TransportationRequest::getRules(),
            SaleRequest::getRules(),
            PurchaseRequest::getRules()
        );
    }
}

Then you can use the single CombinedRequestin your controller method. Of course, if you don't like the static method approach, in your combined request rulesmethod you could just newup each individual request and call the rulesmethod on each of them and merge the results.

然后你可以CombinedRequest在你的控制器方法中使用 single 。当然,如果您不喜欢静态方法方法,在您的组合请求rules方法中,您可以只new启动每个单独的请求并rules在每个请求上调用该方法并合并结果。

class CombinedRequest extends FormRequest
{
    public function rules()
    {
        $transportation = (new TransportationRequest())->rules();
        $sale = (new SaleRequest())->rules();
        $purchase = (new PurchaseRequest())->rules();

        return array_merge(
            $transportation,
            $sales,
            $purchase
        );
    }
}

回答by sharpie89

I know this is a pretty old question, but I got annoyed by not being able to chain form requests together so I made a composer package for this, so you don't have to.

我知道这是一个很老的问题,但我对无法将表单请求链接在一起感到恼火,所以我为此制作了一个作曲家包,所以你不必这样做。

https://github.com/sharpie89/laravel-multiform-request

https://github.com/sharpie89/laravel-multiform-request

回答by Alexey Mezenin

You could concatinate all rules and validate manually:

您可以连接所有规则并手动验证:

$allRules = (new TransportationRequest)->rules() + (new PurchaseRequest)->rules() + (new SaleRequest)->rules();
Validator::make($request->all(), $allRules)->validate();

回答by ab.in

I would create traits containing the rules for each FormRequest - purchase, transporataion and sale. Use the trait in it's specific FormRequest and then when you need all the rules you can use all three traits in the combined FormRequest and merge the rules arrays then.

我将创建包含每个 FormRequest 规则的特征 - 购买、运输和销售。在它的特定 FormRequest 中使用特征,然后当您需要所有规则时,您可以在组合的 FormRequest 中使用所有三个特征,然后合并规则数组。

回答by Leon

I recently came up against this problem, and solved it like this:

我最近遇到了这个问题,并解决了这样的问题:

public function rules()
{
    $request1 = RequestOne::createFrom($this);
    $request2 = RequestTwo::createFrom($this);

    return array_merge(
        $request1->rules(),
        $request2->rules()
    );
}