Skip to content

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
ParameterDescription
objThe value to serialize.
cfgOptions, see below.
fdAn existing FormData to append to. A new one is created when omitted.
preKey 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:

  • undefined is skipped.
  • null becomes an empty string (or is skipped with nullsAsUndefineds).
  • Date becomes an ISO string (toISOString()).
  • File / Blob values are appended as they are.
  • Arrays use key[] (or key[0] with indices); empty arrays are skipped unless allowEmptyArrays.
  • Objects use key[prop] (or key.prop with dotsForObjectNotation).
  • A trailing [] in an object key holding an array is stripped, so { 'ids[]': [1] } does not become ids[][].

Options ​

All options default to false.

OptionDescription
indicesAdd indices to array keys: tags[0], tags[1] instead of tags[].
nullsAsUndefinedsSkip null values instead of sending an empty string.
booleansAsIntegersSend true / false as 1 / 0 (Laravel's boolean rule does not accept "true").
allowEmptyArraysSend an empty array as key[] with an empty value instead of skipping it.
noAttributesWithArrayNotationRepeat the bare key for every array item (tags=a&tags=b).
noFilesWithArrayNotationSame as above, but only for arrays of files.
dotsForObjectNotationUse 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.

Source Code ​