Donations Appreciated

No one has ever become poor by giving. - Anne Frank, diary of Anne Frank

Click here to lend your support to: Laravel Datatables and make a donation at pledgie.com !

EloquentController.php - Advance Filtering


Custom Filter

Id Name Email # of Post Created At Updated At

EloquentController.php

    public function getAdvanceFilter()
    {
        return view('datatables.eloquent.advance-filter');
    }

    public function getAdvanceFilterData(Request $request)
    {
        $users = User::select([
            DB::raw("CONCAT(users.id,'-',users.id) as id"),
            'users.name',
            'users.email',
            DB::raw('count(posts.user_id) AS count'),
            'users.created_at',
            'users.updated_at'
        ])->leftJoin('posts', 'posts.user_id', '=', 'users.id')
        ->groupBy('users.id');

        $datatables =  app('datatables')->of($users)
            ->filterColumn('users.id', 'whereRaw', "CONCAT(users.id,'-',users.id) like ? ", ["$1"]);

        // having count search
        if ($post = $datatables->request->get('post')) {
            $datatables->having('count', $datatables->request->get('operator'), $post);
        }

        // additional users.name search
        if ($name = $datatables->request->get('name')) {
            $datatables->where('users.name', 'like', "$name%");
        }

        return $datatables->make(true);
    }

Javascript

    var oTable = $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: 'https://datatables.yajrabox.com/eloquent/advance-filter-data',
            data: function (d) {
                d.name = $('input[name=name]').val();
                d.operator = $('select[name=operator]').val();
                d.post = $('input[name=post]').val();
            }
        },
        columns: [
            {data: 'id', name: 'users.id'},
            {data: 'name', name: 'users.name'},
            {data: 'email', name: 'users.email'},
            {data: 'count', name: 'count', searchable: false},
            {data: 'created_at', name: 'users.created_at'},
            {data: 'updated_at', name: 'users.updated_at'}
        ]
    });

    $('#search-form').on('submit', function(e) {
        oTable.draw();
        e.preventDefault();
    });