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

Laravel 8中Datatable根据ID为信息状态设置高亮颜色的实现问题

实现方案

着色逻辑放在后端控制器或前端JS中均可实现,两种方案如下:

方案1:后端控制器实现

该方案逻辑集中,维护成本更低,推荐使用。
需修改UserController中index方法代码:一是调整addColumn('status')的判断逻辑,根据关联的statusrecordID返回对应颜色的HTML标签;二是在rawColumns数组中新增status字段,避免Datatable转义HTML内容。
修改后代码:

public function index(){
    $record = User::with('ownership','assetdpa','statusrecord')->where('asset_type_id','=',1)->orderby('id', 'asc')->get();
    if(request()->ajax()){
        return DataTables()::of($record)
        ->addIndexColumn()
        ->addColumn('status', function($record){
            if(!$record->statusrecord){
                return '<span style="color: red">Deactive</span>';
            }
            // 状态与颜色映射关系:Verified对应ID1绿色,Draft对应ID2蓝色,Need Verify对应ID3红色
            $statusConfig = [
                1 => ['text' => 'Verified', 'color' => 'green'],
                2 => ['text' => 'Draft', 'color' => 'blue'],
                3 => ['text' => 'Need Verify', 'color' => 'red']
            ];
            $current = $statusConfig[$record->statusrecord->id] ?? ['text' => '未知状态', 'color' => 'black'];
            return '<span style="color: '.$current['color'].'">'.$current['text'].'</span>';
        })
        ->rawColumns(['action', 'fullOrganisation','fullLocation','fullCategory', 'status'])
        ->make(true);
    }
    return view('asset.index',compact('record'));
}

使用该方案时,前端Datatable无需额外配置status字段的渲染逻辑,直接绑定后端返回的status字段即可。

方案2:前端JS实现

若希望将视图渲染逻辑放在前端处理,可修改index.blade.php中的Datatable配置。原有代码存在语法问题:判断相等误用赋值运算符=、未定义id及data变量,修改后代码如下:

$(document).ready(function(){
    $('#item_table').DataTable({
        columnDefs: [{
            data: 'statusrecord',
            render: function (statusrecord, type, row) {
                if(!statusrecord) {
                    return '<span style="color: red">Deactive</span>';
                }
                let color = 'black';
                let statusText = '未知状态';
                switch(statusrecord.id) {
                    case 1:
                        color = 'green';
                        statusText = 'Verified';
                        break;
                    case 2:
                        color = 'blue';
                        statusText = 'Draft';
                        break;
                    case 3:
                        color = 'red';
                        statusText = 'Need Verify';
                        break;
                }
                return '<span style="color:' + color + '">' + statusText + '</span>';
            }
        }]
    })
})

内容的提问来源于stack exchange,提问作者Aiman Nazri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:45:04