Home > Software design >  How to group some data on basis of two fields in Laravel?
How to group some data on basis of two fields in Laravel?

Time:10-05

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:

Skills History Table

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 >{{ $skillHis->skills->skill_name}}</span>
    </td>
    <td>{{ $skillHis->date }}</td>
    @if ($skillHis->status == 1)
        <td><span >Added</span></td>
    @else
        <td><span >Removed</span></td>
    @endif
</tr>
@endforeach

So as expected in the browser it shown like this:

enter image description here

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):

enter image description here

How can I Achieve that? Thanks!

CodePudding user response:

You need to modify the collection using map

$skillHistories =  SkillsHistory::with('skills')
           ->where('employees_id', $emp_id)
            ->orderBy('date')->get()
            ->groupBy(function ($item, $key) {
              $status = ($item->status == 1) ? 'Added' : 'Removed';
              return $item['date'].'_'.$status;
                            })
                            ->map(function ($group, $key) {
                               
                                $x['date'] = (explode('_', $key))[0];
                                $x['status'] = (explode('_', $key))[1];
                                $x['skills'] = $group;
                                return $x;
                            });

CodePudding user response:

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
    )

)
  • Related