I am building a form with FormData
for sending a file along with other information to a Laravel API, but the file might be null
, according to the rule:
$validator = Validator::make(Request::all(), [
...
"file" => "nullable|mimes:pdf,doc,docx"
]);
And from the front-end, the FormData
being sent:
const data = new FormData();
data.append("name", name);
data.append("instructions", instructions);
data.append("reward", reward);
data.append("deadline", deadline);
data.append("file", file ? file[0] : null);
file
has a default value of null
, but when I check the logs of Request::all()
, I see the following:
[2018-08-18 06:55:13] local.INFO: array (
..
'file' => 'null',
)
Your file looks like an array so what you can do is check if it is an array if yes then assign file[0] otherwise assign file
const data = new FormData();
let fileData = file;
if(Array.isArray(file)){
fileData = file[0];
}else{
fileData = file
}
data.append("name", name);
data.append("instructions", instructions);
data.append("reward", reward);
data.append("deadline", deadline);
data.append("file", fileData);
OR
data.append("name", name);
data.append("instructions", instructions);
data.append("reward", reward);
data.append("deadline", deadline);
data.append("file", Array.isArray(file) ? file[0] : file);