I am trying to create an Excel file from my Database that looks like this :
User Name | User Lastname | Group A | Group B | Group X |
---|---|---|---|---|
John | Doe | X | X | |
Jane | Doe | X |
I have 3 tables : a User table, a Group Table, and a Group Matching table that is martching user_id and group_id as a user can have many groups.
I successfully constructed the header dynamically by querying the group list and appening "User Name" and "User Lastname" to the header array
public function headings(): array
{
$header = array();
$search ="Group";
$groupList = new \App\Models\Group;
$groupList = $groupList::where('name','LIKE',"%{$search}%")->get();;
foreach($groupList as $key=>$value) {
$header[]=$value["name"];
}
array_unshift($header,"User Name", "User Lastname");
return $header;
}
note that I cannot control the number of group that will be output.
Next, I have my collection of records that are returning an array that contains user names, lastnames, and group membership.
public function array(): array
{
$datas = array();
$MyUsers = MyUser::with(['groupMatching'])->get();
foreach($MyUsers as $MyUser) {
$datas[$MyUser->id]["name"] = $MyUser->lastname;
$datas[$MyUser->id]["firstname"] = $MyUser->firstname;
foreach($MyUser->groupMatching as $MyMember) {
$datas[$MyUser->id]["groups"][] = $MyMember->Group_name;
}
}
return $datas;
}
so $datas looks like this :
array:23 [▼ // app/Exports/MyUsersExport.php:31
4 => array:3 [▼
"name" => "Doe"
"firstname" => "John"
"groups" => array:3 [▼
0 => "Group A"
1 => "Group X"
]
5 => array:3 [▼
"name" => "Jane"
"firstname" => "Doe"
"groups" => array:2 [▼
0 => "Group X"
]
]
]
What's the next step to achieve the illustrated output? How can I get an X on matching column name / datas ?
I tried to look around for map functions and some examples but could not find the way to go. I am using laravel 9 and maatwebsite/excel 3.1
Thank you for your help :)
Since you don't have the ability to set a row value for a specific column, I would suggest declaring the $groupList
variable in the class, then filling it in the headings
method. Then in the array
method you cycles all the groups and do a search if the user belongs to that group.
public function array(): array
{
$datas = array();
$MyUsers = MyUser::with(['groupMatching'])->get();
foreach($MyUsers as $MyUser) {
$datas[$MyUser->id][] = $MyUser->lastname;
$datas[$MyUser->id][] = $MyUser->firstname;
foreach ($this->groupList as $groupItem) {
$exists = (bool) $MyUser->groupMatching->firstWhere('Group_name', $groupItem['name']);
$datas[$MyUser->id][] = $exists ? 'X' : '';
}
}
return $datas;
}