I tried to solve this problem for several days. I didn’t go anywhere. On my website there is an opportunity to choose what topics you do at school. The front end works fine, and I can get the result in a table in a column subjects
.
The problem arises when adding several objects: it creates a child for each item that I add. This, when several items have been added, leads to something like this:
[
{
"subject": {
"level": "hl",
"subject": "mathematics"
}
},
[
{
"subject": {
"level": "hl",
"subject": "french"
}
},
[
{
"subject": {
"level": "hl",
"subject": "history"
}
}
]
]
]
As you can see, every time a user adds a topic, a child is created to hold on to all previous topics that have been added. What I'm trying to achieve looks something like this:
[
{
"subject": {
"level": "hl",
"subject": "mathematics"
}
},
{
"subject": {
"level": "hl",
"subject": "french"
}
},
{
"subject": {
"level": "hl",
"subject": "history"
}
}
]
The PHP code that I use to combine the two arrays is as follows:
$input = $request->only(['subject', 'level']);
$user = Auth::user();
$add_subject['subject'] = [
'subject' => $input['subject'],
'level' => $input['level'],
];
$user_subjects = $user->subjects;
$array1 = array($add_subject);
$array2 = array($user_subjects);
$merge = array_merge($array1, $array2);
$user->subjects = $merge;
$user->save();
. ?