Laravel - how to show data with foreach in yajra datatable?

Viewed 1216

I want to show audit trail data in datatables. column old_values and new_values are array in database. i'm using yajra-datatable.

Old_values/new_values value in db something like this

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

But in the view, column old/new_values, it only show the latest array. for example only show var_allowance_2 = 300.00 instead of all value (i.e)

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

var_allowance_1= 500.00

var_allowance_2=300.00

here is the script in blade

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

here is the controller

 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); 
}

If i am not using server side on blade, with using below code on blade, it works. How do I implement it on a server-side datatable?

<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>
1 Answers

In laravel -> controller calling function you can return data table object like this

I have added extra buttons for action to return in the table for the custom column

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);
}

In blade template HTML Part

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

In Js part of the template

    $(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();
            });

up and running example from my live project

In your case data: 'old_values', will be data: 'var_allowance_1',

data: 'new_values', will be data: 'var_allowance_2',

Related