I get a list of Project Objects by doing this
$projects = Project::orderBy('deploymentDate', 'ASC')->get();
The output of the above is something like this
Collection {#292
#items: array:2 [
0 => Project {#293
#attributes: array:15 [
"id" => "4"
"name" => "Something"
"value" => "234"
"user_id" => "1"
"client_id" => "97"
"contact" => "sdfsd"
]
}
1 => Project {#294
#attributes: array:15 [
"id" => "3"
"name" => "Something"
"value" => "6"
"user_id" => "1"
"client_id" => "97"
"contact" => "John Doe"
]
}
]
}
I have removed a lot of the unnecessary data. So you can see I have two projects. The problem is, these projects have relationships with other models, so I need to create an array containing all of this data. So if I do
foreach($projects as $project) {
dd($project->projectType);
}
I can see this
#attributes: array:6 [
"id" => "2"
"additionalInformation" => null
"project_id" => "4"
]
So I have created an array, and I plan on adding the project along with its relationships to this array. At the moment I am trying this
$projectsArray = array();
foreach($projects as $project) {
$projectsArray[] = array(
"Project" => json_decode($project, true)
);
if($project->projectType) {
$projectsArray[] = array(
"Types" => json_decode($project->projectType, true)
);
}
}
The issue with this is that it outputs the following
array:4 [
0 => array:1 [
"Project" => array:15 [
"id" => "4"
"name" => "Something"
"value" => "234"
"user_id" => "1"
"client_id" => "97"
"contact" => "sdfsd"
]
]
1 => array:1 [
"Types" => array:6 [
"id" => 2
"additionalInformation" => null
"project_id" => "4"
]
]
2 => array:1 [
"Project" => array:15 [
"id" => "3"
"name" => "Something"
"value" => "6"
"user_id" => "1"
"client_id" => "97"
"contact" => "John Doe"
]
]
3 => array:1 [
"Types" => array:6 [
"id" => 1
"additionalInformation" => null
"project_id" => "3"
]
]
]
So it is adding the data to the array, but not nesting it as relations. Ideally, I would be after something like this for each project
array:1 [
"Project" => array:2 [
"Project" => array:15 [
"id" => 3
"name" => "Something"
"value" => "6"
"user_id" => "1"
"client_id" => "97"
"contact" => "John Doe"
]
0 => array:1 [
"Types" => array:6 [
"id" => 1
"additionalInformation" => null
"project_id" => "3"
]
]
]
"Project" => ...
]
How could this be achieved?
Thanks
ddis not a builtin. Neither isCollection. This looks like laravel - is it specific to the framework? Please either change the code to show how you reproduced the problem with generic php functions, or add a tag for the specific framework you are using.