objectToFormData
Serializes a (nested) object into a FormData, using the bracket notation PHP/Laravel understands. It is auto-imported, and it is what the *Form methods of useApi use under the hood.
ts
function objectToFormData<T>(obj: T, cfg?: Options, fd?: FormData, pre?: string): FormData| Parameter | Description |
|---|---|
obj | The value to serialize. |
cfg | Options, see below. |
fd | An existing FormData to append to. A new one is created when omitted. |
pre | Key prefix, used for recursion (e.g. to nest everything under data). |
Usage
ts
const fd = objectToFormData({
name: 'Mario',
active: true,
avatar: file, // File / Blob: appended as is
birthday: new Date('2000-01-01'),
tags: ['a', 'b'],
address: { city: 'Milano' },
note: null,
}, { indices: true, booleansAsIntegers: true })
// name=Mario
// active=1
// avatar=<file>
// birthday=2000-01-01T00:00:00.000Z
// tags[0]=a, tags[1]=b
// address[city]=Milano
// note=How values are serialized:
undefinedis skipped.nullbecomes an empty string (or is skipped withnullsAsUndefineds).Datebecomes an ISO string (toISOString()).File/Blobvalues are appended as they are.- Arrays use
key[](orkey[0]withindices); empty arrays are skipped unlessallowEmptyArrays. - Objects use
key[prop](orkey.propwithdotsForObjectNotation). - A trailing
[]in an object key holding an array is stripped, so{ 'ids[]': [1] }does not becomeids[][].
Options
All options default to false.
| Option | Description |
|---|---|
indices | Add indices to array keys: tags[0], tags[1] instead of tags[]. |
nullsAsUndefineds | Skip null values instead of sending an empty string. |
booleansAsIntegers | Send true / false as 1 / 0 (Laravel's boolean rule does not accept "true"). |
allowEmptyArrays | Send an empty array as key[] with an empty value instead of skipping it. |
noAttributesWithArrayNotation | Repeat the bare key for every array item (tags=a&tags=b). |
noFilesWithArrayNotation | Same as above, but only for arrays of files. |
dotsForObjectNotation | Use dots for nested objects: address.city instead of address[city]. |
With useApi
postForm, putForm, patchForm (and their $ variants) build the body with useApi().buildFormData(data, options), which calls objectToFormData with these defaults:
ts
{ nullsAsUndefineds: false, booleansAsIntegers: true, indices: true }The options are read from the same object as the fetch options, so you can override them per call:
ts
await useApi().$postForm('users', model, { indices: false })putForm and patchForm send a POST with _method: 'put' / 'patch', so files can be uploaded on update with Laravel's method spoofing.