You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Blade中如何高亮IP重复的表格数据行?

在Blade模板中高亮IP重复的表格行

问题描述

我拥有name、email、username和ip字段,请问如何在Blade模板中检查并高亮IP地址重复的表格行?

现有控制器代码

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

现有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

解决方案

1. 控制器中统计IP出现次数

先在控制器内计算每个IP的重复次数,将统计结果与参与者数据一同传递给视图,避免在模板中重复计算,提升性能:

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

// 统计每个IP的出现次数
$ipCounts = $promo->participants->countBy('ip');

return view('你的视图名称', compact('promo', 'ipCounts'));

2. 修改Blade模板实现高亮

首先修正原模板的问题:当前代码会为每个参与者创建独立表格,导致表头重复显示,需将<table>标签移至循环外部。随后根据$ipCounts判断当前IP是否重复,为重复行添加高亮类:

@if($promo->participants->count() > 0)
    <table>
        <tr class="align-middle">
            <td>Name</td>
            <td>Email</td>
            <td>Username</td>
            <td>IP</td>
        </tr>
        @foreach($promo->participants as $participant)
            <tr class="{{ $ipCounts[$participant->ip] > 1 ? 'bg-warning' : '' }}">
                <td>{{ $participant->name }}</td>
                <td>{{ $participant->email }}</td>
                <td>{{ $participant->username }}</td>
                <td>{{ $participant->ip }}</td>
            </tr>
        @endforeach
    </table>
@endif

3. 自定义高亮样式(可选)

若不使用Bootstrap的bg-warning类,可自行定义CSS样式:

.highlight-row {
    background-color: #fff3cd; /* 可根据需求调整颜色 */
}

然后将模板中的bg-warning替换为自定义类名:

<tr class="{{ $ipCounts[$participant->ip] > 1 ? 'highlight-row' : '' }}">

内容的提问来源于stack exchange,提问作者Ryan R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:35:12