Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mecjos's avatar

Sending and Retrieving Object Array in formData

Hi.. I want to send object array data in javascript formData object to laravel api with following code:

data () {
	return {
		formData: {
			shifts: [{ name: 'Shift-1', shift_start: '09:00', shift_end: '18:00' }, .....]
		}
	}
}
....
const formData = new FormData()
formData.append('shifts',  this.formData.shifts)
const params = {
        url: this.selectedItem ? '/machines/' + this.selectedItem.id : '/machines',
        data: formData,
        moduleName: 'machine'
      }
this.$store.dispatch('AddData', params)

But this way I cant' get request as follows:

if ($request->has('shifts')) {
            foreach($request->shifts as $shift) {
                Machine::find(1)->shifts()->create($shift); // shifts() is hasMany relation
            }
        }

How to do that in proper way?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

When appending an array to a FormData object, each element of the array should be appended separately with the same key. In this case, the "shifts" array should be looped through and each element should be appended with the same key "shifts". Here's an example:

const formData = new FormData()
this.formData.shifts.forEach((shift, index) => {
  formData.append(`shifts[${index}][name]`, shift.name)
  formData.append(`shifts[${index}][shift_start]`, shift.shift_start)
  formData.append(`shifts[${index}][shift_end]`, shift.shift_end)
})

Then, in the Laravel controller, the "shifts" parameter can be accessed as an array of arrays:

if ($request->has('shifts')) {
  foreach ($request->input('shifts') as $shift) {
    Machine::find(1)->shifts()->create($shift);
  }
}
mecjos's avatar

AI rally good.. I found another solution also,

formData.append('shifts',  JSON.stringify(this.formData.shifts))

foreach (json_decode($request->shifts, true) as $shift) {
            $createMachine->shifts()->create($shift);
        }

Please or to participate in this conversation.