phplaravel

How to solve the problem of dynamic rowspan problem in table in laravel


I am trying to show the table like below image enter image description here And i write the logic for this table creation is below

 @foreach($users as $key => $user)
            <tr>
              <td>{{$key+1}}</td>
              <td>{{$user->name}}</td>
              <td rowspan="{{count($users->where('area',$user->area))}}">
                 {{$user->userarea->name}}</td>

              <td rowspan="{{count($user->candidate->election->candidates)}}">{{$user->candidate->election->name}}</td>
            </tr>
            @endforeach
             </tbody>

But this code produce me the following code like this enter image description here Here The Election and Candidate has one to many relationships and candidate and user has one one to one relationshipHelp me achieve my expected results.


Solution

  • You could keep track of which elections/area's have been rendered already. This could be done by creating an array containing a reference to these objects. Then in the template just add an if statement checking whether an election/area has been rendered:

    <?php $renderedElections = []; ?>
    <?php $renderedAreas = []; ?>
    @foreach($users as $key => $user)
    <tr>
        <td>{{$key+1}}</td>
        <td>{{$user->name}}</td>
        @if (!in_array($user->userarea->name, $renderedAreas))
            <?php $renderedElections[] = $user->userarea->name ?>
            <td rowspan="{{count($user->userarea->name)}}">
                {{$user->userarea->name}}
            </td>
        @endif
        @if (!in_array($user->candidate->election->name, $renderedElections))
            <?php $renderedElections[] = $user->candidate->election->name ?>
            <td rowspan="{{count($user->candidate->election->candidates)}}">
                {{$user->candidate->election->name}}
            </td>
        @endif
    </tr>
    

    This is not the best solution, but its simple and easy. For this to work, the users must be sorted perfectly by election and area.