简体   繁体   English

根据不同要求进行模型验证

[英]Model validation on different request

I have several models all of which have a create page. 我有几种模型,所有模型都有一个创建页面。 When a model is created, I do not perform any validation. 创建模型时,我不执行任何验证。 This is because I allow the user at any time to go back and add to things. 这是因为我允许用户随时返回并添加到事物中。

However, at some point, I provide a button to the user 但是,有时我会向用户提供一个按钮

<a href="{{ route('projects.push', $project->id) }}" class="btn btn-info pull-right" data-token="{{ csrf_token() }}">
    Push
</a>

All of the models in question are related to the Project model. 所有有问题的模型都与项目模型有关。 When they click the push button, I am going to send the Models to an external system. 当他们单击按钮时,我将把模型发送到外部系统。 However, at this point I need to validate that the models being sent have all the required data. 但是,在这一点上,我需要验证发送的模型是否具有所有必需的数据。 I know about validation on a model, but this is when they are created. 我知道有关模型的验证,但这是在创建模型时进行的。 Is it possible to validate them on a completely different action? 是否可以通过完全不同的动作验证它们?

Thanks 谢谢

Of course it is possible. 当然可以。 It would be smart to store your rules and/or messages inside you model as a static function. 将您的规则和/或消息存储在模型中作为静态函数是很明智的。 An example would be: 一个例子是:

// Project model
public static function rules()
{
    return [
        'field1' => 'rules1..',
        'field2' => 'rules2..'
    ];
}

Then you can retrieve your rules anywhere in your application: 然后,您可以在应用程序中的任何位置检索规则:

Validator::make($fields, Project::rules());

One last thing. 最后一件事。 You said you validate your model when it already has been created. 您说您已经在创建模型时验证了模型。 I don't know if putting the entire retrieved model variable instead of $fields will work. 我不知道是否将整个检索到的模型变量而不是$fields起作用。 Example: 例:

$project = Project::find($id);

// Try this
Validator::make($project, Model::rules());

// Otherwise try this
Validator::make($project->attributes, Model::rules());

Hope this helps :) 希望这可以帮助 :)

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

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