Here I’m trying to keep track of my Employees Skills like when they are added, when removed and then new skills are added.
So, I’m getting storing them in the database as follows:
Then Retrieving the data as follows:
$skillHistories = SkillsHistory::with('skills')->where('employees_id', $emp_id)->orderBy('date')->get();
And then showing them in the blade as:
@foreach ($skillHistories as $skillHis) <tr> <td>{{ $loop->index + 1 }}</td> <td> <span class="badge rounded-pill bg-primary m-l-15">{{ $skillHis->skills->skill_name}}</span> </td> <td>{{ $skillHis->date }}</td> @if ($skillHis->status == 1) <td><span class="badge rounded-pill bg-success">Added</span></td> @else <td><span class="badge rounded-pill bg-danger">Removed</span></td> @endif </tr> @endforeach
So as expected in the browser it shown like this:
But I want to group all the added skills on a date and all the removed skills on a date in an individual group. And I want to order the list on basis of date.
Kind of as follows(This is static):
How can I Achieve that? Thanks!
Advertisement
Answer
You can try this:
$skillHistories = SkillsHistory::with('skills')->where('employees_id', $emp_id)->orderBy('date')->get(); $array = []; foreach ($skillHistories as $key => $skillsHis) { $array[$skillsHis->date]['date'] = $skillsHis->date; $array[$skillsHis->date]['skills'][] = $skillsHis->skills->skill_name; $array[$skillsHis->date]['status'] = $skillsHis->status; } $skills_array = array_values($array);
Result:
Array ( [0] => Array ( [date] => 2022-10-01 [skills] => Array ( [0] => NP [1] => CL [2] => CM [3] => NAP [4] => NLM ) [status] => 1 ) [1] => Array ( [date] => 2022-10-04 [skills] => Array ( [0] => NP ) [status] => 0 ) )