Datatable Server Side Processing (Laravel)

Javascript:

var dt_members = function(){
    var $c = null;
    var $t = null;
    var datatable = null;

    function init(){
        $c = $(".main-content");
        $t = $c.find('#dt_members');

        $t.find('input[name="sell_id"]').on('click', function(e){
            var $this = $(this);
            if($this.prop('checked') == true){
                total += parseInt($this.data('qty'));
            }else{
                total -= parseInt($this.data('qty'));
            }

            refresh_total();
        });

        init_dt();
    }

    function init_dt(){
        datatable = $t.DataTable({
            "searching": true,
            "info": true,
            "lengthChange": true,
            "paging": true,
            'serverSide': true, 
            'processing': true, 
            "ajax": {
                'url': base_url + 'admin/ajax/members',
                'data': function(d){
                    //var $c = $('#c-tabs-1');
                    //d.keyword = get_value('keyword', $c);
                }
            },
            //"order": [[ 6, "asc" ], [ 5, "" ]], 
            "columnDefs": [
                {
                    "targets": [ 1 ],
                    "visible": true,
                    "searchable": false
                }
            ], 
            "drawCallback": function( settings ) {
                var api = this.api();
                //wrap.loaded(settings);
                loaded(settings);
            }, 
            'initComplete': function(settings, json){
                //loaded(settings);
            },
            createdRow: function( row, data, dataIndex ) {
                //data is a value array of this row
                var $row = $(row);
                $row.addClass(data[0]);
            },
            "language" : {
                "url": "/plugins/datatable_zhtw.json"
            }
        });
    }

    function loaded(oSettings){
        $t.find('.action_edit').on('click', function(e){
            e.preventDefault();
            var $this = $(this);
            var member_id = $this.data('id');
            
            member_app.show(member_id, 'edit');
        });

        $t.find('.action_buy').on('click', function(e){
            e.preventDefault();
            var $this = $(this);
            var member_id = $this.data('id');
            
            ticket_app.show(member_id, 'buy');
        });

        $t.find('.action_sell').on('click', function(e){
            e.preventDefault();
            var $this = $(this);
            var member_id = $this.data('id');
            
            ticket_app.show(member_id, 'sell');
        });
    }

    function refresh(reset_page){
		if(typeof reset_page == 'undefined'){
			reset_page = false;
		}
		datatable.ajax.reload(null, reset_page);
    }

    return {
        init: init, 
        refresh: refresh
    }
}();

Config:

<?php
return [
    'member_table' => [
        'id' => ['ID', true, 'int'],
        'name' => ['姓名', true, 'int'],
        'email' => ['Email', true, 'string'],
        'phone' => ['電話', true, 'string'],
        'pid' => ['身份證', true, 'string'],
        'status' => ['狀態', true, 'int'],
        'created_time' => ['建立時間', true, 'datetime'], 
        'action' => ['動作', true, 'string']
    ], 
];

 

Controller:

    protected function datatable_response($total, $filtered_total, $data=[], $draw=0){
        header('Content-Type: application/json');

        $out = array();
        $out['draw'] = $draw;
        $out['recordsTotal'] = $total;
        $out['recordsFiltered'] = $filtered_total;
        $out['data'] = $data;
     
        echo json_encode($out);
        exit();
    }

    public function members(Request $req){
        $this->check_login();

        $draw = $req->input('draw');
        $start = $req->input('start');
        $length = $req->input('length');
        $search = $req->input('search');
        $keyword = $search['value'];

        //Get sorting array with column name
        $fields = Config::get('admin.member_table');
        $order = $req->input('order');
        $sorting = MemberM::datatable_sorting($fields, $order);
        //logg($sorting);

        $options = [
            'start' => $start, 
            'limit' => $length, 
            'sort' => $sorting, 
            'keyword' => $keyword
        ];
        $total = MemberM::items($options, MemberM::DT_TOTAL);
        $filtered_total = MemberM::items($options, MemberM::DT_FILTERED);
        $members = MemberM::items($options);

        $members = MemberM::datatable_data($members);

        $this->datatable_response($total, $filtered_total, $members, $draw);
    }

Model:

    static function items($options, $return_type=0){
        $result = DB::table('member');

        if($return_type == self::DT_TOTAL){
            return $result->count();
        }

        $keyword = val($options, 'keyword');
        if($keyword != false){
            $result = $result->where(function($query) use ($keyword){
                $find = '%' . $keyword . '%';
                $query->orWhere('name', 'like', $find);
                $query->orWhere('email', 'like', $find);
                $query->orWhere('phone', 'like', $find);
                $query->orWhere('pid', 'like', $find);
            });
        }

        if($return_type == self::DT_FILTERED){
            return $result->count();
        }

        if(val($options, 'sort') != false){
            $sorting = val($options, 'sort');
            foreach ($sorting as $key => $value) {
                $result = $result->orderBy($key, $value);
            }
        }else{
            $result = $result->orderBy('created_time', 'desc');
        }

        $result = $result->skip($options['start'])
            ->take($options['limit'])
            ->get();

        return $result;
    }

    static function datatable_sorting($columns, $order){
        //$columns = $this->config->item('adm_page_columns');
        //$order = $this->input->get('order');
     
        $sort = array();
        foreach($order as $key => $item){
            $col_index = $item['column'];
            $dir = $item['dir'];
     
            $column = null;
            $column_key = null;
            $i = 0;
            foreach ($columns as $key => $item) {
                if($i == $col_index){
                    $column = $item;
                    $column_key = $key;
                    break;
                }
                $i++;
            }
     
            $sort[$column_key] = $dir;
        }
     
        return $sort;
    }

    static function datatable_data($data){
        $fields = Config::get('admin.member_table');

        $new_data = array();
        foreach($data as $item){
            $item_values = [];

            foreach ($fields as $key => $field) {
                $value = val($item, $key);

                if($key == 'status'){
                    $value = trans('front.member_status.' . $item->status);
                }

                if($key == 'action'){
                    $value = '<div class="dropdown">
                            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                選擇
                                <span class="caret"></span>
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
                                <li><a href="#" class="action_edit" data-id="' . $item->id . '">修改</a></li>
                                <li><a href="#" class="action_buy" data-id="' . $item->id . '">下買單</a></li>
                                <li><a href="#" class="action_sell" data-id="' . $item->id . '">下賣單</a></li>
                            </ul>
                        </div>';
                }

                $item_values[] = $value;
            }

            array_push($new_data, $item_values);
        }

        return $new_data;
    }