skip to Main Content

Hello I have these columns ‘name’, ’email’, ‘username’ and ‘ip’ how would I check or highlight table row in blade if records has same ip?

This is my controller

 $promo = Promo::with(['participants' => function ($q) {
            $q->orderBy('winner', 'desc')->orderBy('created_at', 'desc');
        }])->find($id);

And this is my blade

@if($promos->participants->count() > 0)
    @foreach($promos->participants as $participant)
    <table>
      <tr class="align-middle">
        <td>Name</td>
        <td>Email</td>
        <td>Username</td>
        <td>IP</td>
      </tr>
      <tr>
        <td>{{$participant->name}}</td>
        <td>{{$participant->email}}</td>
        <td>{{$participant->username}}</td>
        <td>{{$participant->ip}}</td>
      </tr>
    </table>
    @endforeach
@endforeach

2

Answers


  1. Do like this

    $ipList will store IPs when foreach runs and keeps checking whether they exist. If yes, add class duplicate-row to the <tr>

    $ipList = [];
    @foreach($promos->participants as $participant)
      <tr class="align-middle @if(in_array($participant->ip, $ipList)) duplicate-row @endif">
        <td>{{$participant->name}}</td>
        <td>{{$participant->email}}</td>
        <td>{{$participant->username}}</td>
        <td>{{$participant->ip}}</td>
      </tr>
      @if(!in_array($participant->ip, $ipList))
        <?php array_push($ipList, $participant->ip); ?>
      @endif
    @endforeach
    

    In CSS you can add

    .duplicate-row {
      background-color: red;
    }
    
    Login or Signup to reply.
  2. Another way is to get duplicates by taking advantage of Larvel’s collection and have them passed in view.

    $ips = $promos->participants->pluck('ip');
    $duplicateIps = $ips->duplicates()->unique()->all();
    

    So in your blade you would just need to check

    @if($promos->participants->isNotEmpty())
    @foreach($promos->participants as $participant)
    <table>
      <tr class="align-middle">
        <td>Name</td>
        <td>Email</td>
        <td>Username</td>
        <td>IP</td>
      </tr>
      <tr @class(['duplicate-row' => in_array($participant->ip, $duplicateIps)]>
        <td>{{$participant->name}}</td>
        <td>{{$participant->email}}</td>
        <td>{{$participant->username}}</td>
        <td>{{$participant->ip}}</td>
      </tr>
    </table>
    @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search