简体   繁体   中英

Laravel validation of optional fields

I currently have a few validation rules as follows:

\Route::post("/logError", "LogController@logError");

 //In LogController
 public function logError(Request $request) { 
    $rules = [
        "name" => "required", 
        "message" => "required",
        "level" => "in:info,debug,error"
    ];

    $this->validate($request,$rules);
    // Log the message or do whatever
});

This works fine for inputs like

[ "name"=>"Not found", "message" => "Element not found", "level" => "error" ]
[ "name"=>"Not found", "message" => "Element not found" ]` 

However it throws an exception for inputs like

[ "name"=>"Not found", "message" => "Element not found", "level" => "randomgibberish" ]

My question is, since "level" is optional, is there a built-in way to validate the input and just remove optional elements that are not valid from it instead of throwing a validation exception? If not would I have to override the controller validation method to achieve this?

The validator does not modify the request input data, you need to make some sort of middleware or function in your controller that checks for the input parameters and compares them with the ones you want Laravel to check.

So yes, I think you'll need to extend the validation method, or maybe try with an helper function that does only that.

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