微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel - 如何在 yajra 数据表中使用 foreach 显示数据?

如何解决Laravel - 如何在 yajra 数据表中使用 foreach 显示数据?

我想在数据表中显示审计跟踪数据。列 old_values 和 new_values 是数据库中的数组。我正在使用 yajra-datatable。

db 中的 Old_values/new_values 值是这样的

{"updated_at":"2021-05-03 09:30:17.248","var_allowance_1":"500.00",**"var_allowance_2":"300.00"**}

但是在视图中,old/new_values 列中,它只显示最新的数组。例如只显示 var_allowance_2 = 300.00 而不是所有值(即)

updated_at = 2021-05-03 09:30:17

var_allowance_1= 500.00

var_allowance_2=300.00

这是刀片中的脚本

 <script>
    $(document).ready(function(){
    
        $('#user_table').DataTable({
            processing: true,serverSide: true,ajax: {
                url: "{{url('/')}}/report/data",type: "GET",'data': function ( d ) {
                    d._token = "{{ csrf_token() }}";
                    d.date1 = $('#date1').val();
                    d.date2= $('#date2').val();
                }
    
            },columns: [
                {
                    data: 'DT_RowIndex',name: 'DT_RowIndex'
                },{
                    data: 'auditable_type',name: 'auditable_type'
                },{
                    data: 'event',name: 'event'
                },{
                    data: 'user_id',name: 'user_id'
                },{
                    data: 'created_at',name: 'created_at'
                },{
                    data: 'old_values',name: 'old_values'
                },{
                    data: 'new_values',name: 'new_values'
                },]
        });
         });
    </script>

这里是控制器

 public function audits_data(Request $request) 
 {
      
    $user = Auth::user();
    $date1  = $request->input('date1');
    $date2  = $request->input('date2');

   
    $user = Auth::user();
    
    $data = \OwenIt\Auditing\Models\Audit::select(['id','event','created_at','auditable_type','user_id','old_values','new_values'])->orderBy('updated_at','DESC')->whereDate('created_at','>=',$date1)->whereDate('created_at','<=',$date2)->get();
       
        return DataTables::of($data)
            ->addindexColumn()
            ->addColumn('old_values',function ($data) {
                
                if (is_array($data->old_values) || is_object($data->old_values))
                {
                    $old = [];
                    foreach($data->old_values as $attribute => $value)
                    {
                        "<b>$attribute = </b>$value<br>"; 
                    }
                } 
                return $old;
            })

            ->addColumn('new_values',function ($data) {
                if (is_array($data->new_values) || is_object($data->new_values))
                {
                    $new = [];
                    foreach($data->new_values as $attribute => $value)
                    {
                        $new= "<b>$attribute = </b>$value<br>";
                    }
                    return $new;
                } 
                 
            })
            ->rawColumns(['old_values','new_values'])
            ->make(true); 
}

如果我不在刀片上使用服务器端,在刀片上使用以下代码,它就可以工作。 如何在服务器端数据表上实现它?

<td>
       @if (is_array($audit->old_values) || is_object($audit->old_values))
         @foreach($audit->old_values as $attribute => $value)
           <b>{{ $attribute }} =</b> {{ $value }}<br>
         @endforeach
      @endif
</td>

解决方法

在laravel -> 控制器调用函数中你可以像这样返回数据表对象

我在自定义列的表格中添加了额外的操作按钮以返回

public function getProducts()
    {
    $products = ProductModel::all();
            return Datatables::of($products)->addColumn('action',function ($products) {
                
                //create links for edit and delete functionality
                return '<a href="'.route("product.save",['uuid' => $products->product_id]).'" class="btn btn-xs waves-effect delete-record"><i class="material-icons col-blue">mode_edit</i></a>
                        <a href="'.route("product.inactive",['uuid' => $products->product_id]).'" onclick="deleteRecord('.$products->product_id.',this,event);   " class="btn btn-xs waves-effect"><i class="material-icons col-red">delete</i></a>';
            })
            ->addIndexColumn()
            ->make(true);
}

在刀片模板 HTML 部分

<div class="body">
<div class="table-responsive">
    <table id="product-table" class="table table-bordered table-striped table-hover dataTable">
        <thead>
            <tr>
                <th>#</th>
                <!--th>Product ID</th-->
                <th>Product Name</th>
                <th>Product System</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </thead>
    </table>
</div>

在模板的 Js 部分

    $(document).ready(function(){
                //Exportable table
               var productDT =  $('#product-table').DataTable({
                    responsive      : true,dom             : 'Blfrtip',autoWidth       : true,paging          : true,pagingTypeSince : 'numbers',pagingType      : 'full_numbers',processing      : true,serverSide      : true,ajax: '{!! route('product.data') !!}',columns: [
                        { data: 'DT_RowIndex',name: 'DT_RowIndex' },//{ data: 'product_id',name: 'product_id' },{ data: 'product_name',name: 'product_name' },{ data: 'product_system',name: 'product_system' },{ data: 'is_active',name: 'is_active' },{data: 'action',name: 'action',orderable: false,searchable: false}
                    ],buttons: [
                        'copy','csv','excel','pdf','print'
                    ]
                });

//search textbox filter code
                productDT.on( 'order.dt search.dt',function () {
                    productDT.column(0,{search:'applied',order:'applied'}).nodes().each( function (cell,i) {
                        cell.innerHTML = i+1;
                    });
                }).draw();
            });

我的实时项目中的启动和运行示例

就你而言 data: 'old_values', 将是 data: 'var_allowance_1',

data: 'new_values', 将是 data: 'var_allowance_2',

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。