Search code examples
laraveldatatablelaravel-8laravel-query-builder

Can't get user_id value Laravel Query


I can't call user_id in my view page using datatable, when I change the select('name') into select('user_id') or select('*') it also show error DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Whats wrong with my code? thanks in advance

I have a controller contain following code

public function TeamTask(Request $request)
    {
      
        if ($request->ajax()) {
            $data = DB::table('posts')->select('name')->selectraw('count(user_id) as total')->selectRaw('SUM(status = "Done") as done')->where('div',  Auth::user()->div)->groupBy('name')->get();
            return Datatables::of($data)
                ->addColumn('action', function ($row) {

                    $btn = ' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $row->name . '" data-original-title="Detail" class="btn btn-success mr-1 btn-sm detailProduct"><span class="fas fa-info"></span></a>';

                    return $btn;
                })
                ->rawColumns(['action'])
                ->addIndexColumn()
                ->make(true);
        }

        return view('task.teamTask',);
    }

my view

<script type="text/javascript">
    $(function() {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        var table = $('.data-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('team.task') }}",

            columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex',
                    orderable: false,
                    searchable: false,
                },
                {
                    data: 'name',
                    name: 'name',
                    orderable: false,
                },
                {
                    data: 'user_id',
                    name: 'user_id',
                    orderable: false,
                },
                {
                    data: 'total',
                    name: 'total',
                    orderable: false,
                },
                {
                    data: 'done',
                    name: 'done'
                },
                {
                    data: 'action',
                    name: 'action'
                },

            ]
        });

    });
</script>

I can't call user_id in my view page using datatable, when I change the select('name') into select('user_id') or select('*') it also show error DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Whats wrong with my code? thanks in advance


Solution

  • Add ->groupBy('user_id') in your query, this should fix your problem