I have this sample JavaScript:
let data = new FormData(); data.set('mode_id', ''); data.set('start', null); axios({ method: 'POST', url: '/test', data: data, headers: { 'Content-Type': 'multipart/form-data' } })
This is the controller endpoint in Laravel:
public function store(Request $request) { Debugbar::info($request->all()); $request->validate([ 'start' => 'required', 'mode_id' => 'required', ]);
To my surprise, the validation for parameter mode_id
failed, but not for parameter start
.
From Debugbar, I find that start
value is a string "null"
.
[ "mode_id" => null "start" => "null" ]
Why and where is FormData null converted to “null”?
If I do a PHPUNIT test
$response = $this->->post('/test', [ 'mode_id' => '', 'start' => null, ]);
Both parameter mode_id
and start
fail in validation, as expected.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Okay, so I found it here https://developer.mozilla.org/en-US/docs/Web/API/FormData/set:
formData.set(name, value);
Parameters
name
The name of the field whose data is contained in value.value
The field's value. This can be a USVString or Blob (including subclasses such as File). If none of these are specified the value is converted to a string.
In other words, one cannot set null
as a value with FormData. I have to catch on the FrontEnd a null value, replace it by an empty string and Laravels Middleware IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull
will convert this back to null
.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0