To flatten an Eloquent collection with relationships and preserve the keys, you can use the map method along with the toArray method. Here's an example:
$flattened = $orgs->map(function ($org) {
return array_merge($org->toArray(), $org->profile->toArray());
});
This code will iterate over each item in the $orgs collection and merge the attributes of the organization and its profile into a single array. The toArray method is used to convert the models into arrays.
The resulting $flattened collection will have the desired flattened structure, preserving the keys:
Illuminate\Support\Collection {
all: [
[
"id" => 1,
"name" => "ABC Corp",
"organization_id" => 1,
"ein" => "80-XXXXXXX",
],
[
"id" => 2,
"name" => "XYZ Corp",
"organization_id" => 2,
"ein" => "85-XXXXXXX",
],
],
}
This approach allows you to flatten the data and preserve the keys without manually mapping each attribute.