How can I send a Form like this using Fetch API to a laravel endpoint: The problem I have is that I can't get the file and inputs with the array name "[]" at the same time. I tried to loop through each element of the form and create a json object but when there is a file input in the form it makes it fail because you must send the data as application/json
format which you have to JSON.stringyfy(data)
which causes the file input to disapear.
I also tried using FormData()
which is working perfectly fine with files and other normal inputs but when it comes to the inputs with array name name[]
or event price[10]
or `price[1][], It doesnt work. What is the best approach to send this kind of form?
<form action="/end-point">
<input type="text" name="title" value="my article title">
<textarea name="body" id="" cols="30" rows="10">THis is the body</textarea>
<input type="checkbox" name="facilities[]" value="1">
<input type="checkbox" name="facilities[]" value="2">
<input type="radio" name="option[]" value="3">
<input type="radio" name="option[]" value="4">
<input type="text" name="name[]" value="test1">
<input type="text" name="name[]" value="test2">
<select name="service_id[]">
<option value="1">Service1</option>
<option value="2">Service2</option>
</select>
<select name="service_id[]">
<option value="1">Service1</option>
<option value="2">Service2</option>
</select>
<select name="service_id[]">
<option value="1">Service1</option>
<option value="2">Service2</option>
</select>
<input type="file" name="picture">
</form>
THe Format I need in the laravel endpoint
[
"title" => "my article title"
"body" => "THis is the body"
"facilities" => array:2 [▼
0 => "1"
1 => "2"
]
"option" => array:1 [▼
0 => "3"
]
"name" => array:2 [▼
0 => "test1"
1 => "test2"
]
"service_id" => array:3 [▼
0 => "1"
1 => "1"
2 => "1"
]
"picture" => Illuminate\Http\UploadedFile {#244 ▼
-test: false
-originalName: "m16.jpg"
-mimeType: "image/jpeg"
-error: 0
#hashName: null
path: "C:\wamp64\tmp"
filename: "php87C8.tmp"
basename: "php87C8.tmp"
pathname: "C:\wamp64\tmp\php87C8.tmp"
extension: "tmp"
realPath: "C:\wamp64\tmp\php87C8.tmp"
aTime: 2020-07-02 04:41:33
mTime: 2020-07-02 04:41:33
cTime: 2020-07-02 04:41:33
inode: 3096224744035967
size: 25467
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\wamp64\tmp\php87C8.tmp"
}
]