简体   繁体   中英

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. Example:

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

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

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

Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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