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

vincent15000's avatar

Problem with nested array datas in a form

Hello,

I have this problem.

In a form, I have to write the studies for each year.

There can be several years and each year can have several diplomas.

Here is my code (with AlpineJS).

<div class="flex flex-col gap-4" x-data="{ studies: {{ json_encode($therapist->studies) }} }">
	<template x-for="(study, studyIndex) in studies" :key="studyIndex">
		<div class="flex gap-4">
			<div>
				<input class="outline-none w-40 p-2 text-black rounded-lg" type="text" placeholder="Année" name="studies[][year]" x-model="study.year">
			</div>

			<div class="w-full">
				<ul class="flex flex-col gap-4">
					<template x-for="(diploma, diplomaIndex) in study.diplomas" :key="diplomaIndex">
						<li>
							<div class="flex items-center gap-4">
								<input class="outline-none w-full p-2 text-black rounded-lg" type="text" placeholder="Diplôme" name="studies[][diplomas][]" x-model="diploma">

								<span class="text-red-600"><i class="fa-solid fa-trash-alt"></i></span>
							</div>
						</li>
					</template>
					<li>
						<div class="flex items-center gap-4">
							<input class="outline-none w-full p-2 text-black rounded-lg" type="text" placeholder="Diplôme" name="speciality">

							<span class="text-red-600"><i class="fa-solid fa-trash-alt"></i></span>
						</div>
					</li>
				</ul>
			</div>
		</div>
	</template>

	<div class="flex gap-4">
		<div valign="top">
			<input class="outline-none w-40 p-2 text-black rounded-lg" type="text" placeholder="Année" name="year">
		</div>

		<div class="w-full" valign="top">
			<ul class="flex flex-col gap-4">
				<li>
					<div class="flex items-center gap-4">
						<input class="outline-none w-full p-2 text-black rounded-lg" type="text" placeholder="Diplôme" name="speciality">

						<span class="text-red-600"><i class="fa-solid fa-trash-alt"></i></span>
					</div>
				</li>
			</ul>
		</div>
	</div>
</div>

Blank fields will be ignored.

This is what I'd like to have in my request when I do dd($request->studies).

"studies" => [
	0 => [
		"year" => 2020,
		"diplomas" => [
			"0" => "First diploma",
			"1" => "Second diploma",
		]
	]
	1 => [
		...
	]
]

I'm in trouble with this code for some hours without finding any solution.

If you could help me, it would be great ;).

Thanks a lot.

Vincent

0 likes
1 reply
vincent15000's avatar
vincent15000
OP
Best Answer
Level 63

Here it is, I just found the solution.

I had to add the study index.

:name="'studies['+studyIndex+'][diplomas][]'"

Please or to participate in this conversation.