Laravel与ajax和json的分页

时间:2017-07-20 21:31:08

标签: php jquery json ajax laravel

我有四个字段可以在我的laravel模型上实现过滤器。我使用ajax从模板刀片中获取响应数据并返回json响应。我的功能:

public function displayTable()
{
    // This four variables get response from ajax
    // The same happens with $this->request->has('instituicao')

    $cpf = $this->request->get('cpf', '');
    $operacao = $this->request->get('operacao', '');
    $dataInicio = $this->request->get('dataInicio', '');
    $dataFim = $this->request->get('dataFim', '');

    $this->validate($this->request, [
        'instituicao' => ['nullable', 'integer', Rule::exists('instituicoes', 'id')],
    ]);

    $auditorias = Audit::with('user')
        ->whereHas('user', function (Builder $q) use ($cpf, $dataFim, $dataInicio) {
            if ($cpf != '') {
                $q->where('cpf', $cpf);
            }
            if ($dataInicio != '' and $dataFim != '') {
                $q->where('created_at', '>=', $dataInicio)
                    ->where('updated_at', '<=', $dataFim);
            }

            $q->when($this->request->has('instituicao'), function (Builder $query) {
                $query->whereHas('perfis', function (Builder $query) {
                    $query->where('tipo', '!=', 'administrador');
                });
            });
        })
        ->get()->filter(function ($item) use ($operacao) {
            if ($operacao != '') {
                return $item->event == $operacao;
            } else {
                return $item;
            }
        })->when($this->request->has('instituicao'), function (Collection $collection) {
            return $collection->filter(function ($auditoria) {
                return $auditoria->user->perfis->contains(function ($perfil) {
                    return $perfil->papel->instituicao->id == $this->request->get('instituicao');
                });
            });
        })->map(function ($item) {
            $auditable_type = explode(
                '\\', $item->auditable_type
            );

            $item->auditable_type = end($auditable_type);

            if ($item->event == 'created') {
                $item->event = 'Criação';
            } elseif ($item->event == 'updated') {
                $item->event = 'Atualização';
            } else {
                $item->event = 'Remoção';
            }

            return $item;
        })->values();

    return response()->json([
        'data' => $auditorias,
    ]);
}

例如,当我用paginate(10)替换get()方法时,我的filter()响应不起作用。

我的模板刀片是这样的:

                    <table id="tabela" class="table table-striped dataTable" style="width: 100%">
                        <thead>
                        <tr>
                            <th>Usuário Responśavel</th>
                            <th>CPF Usuário Responśavel</th>
                            <th>Operação</th>
                            <th>Tipo de Modificação</th>
                            <th>Data de Criação</th>
                            <th>Data de Modificação</th>
                        </tr>
                        </thead>
                        <tbody id="corpoTabela"></tbody>
                    </table>

<!-- Here I have the scripts -->
<!-- This div is the field (Select2), 
 who is selected and return his data response, 
as the others filds data -->

$('#operacao').on('change', function () {
        var operacao = $('#operacao').val();
        var cpf = $('#cpf').val();
        var instituicao = $('#escolas').val();
        dataInicio = $('#dataInicio').val();
        dataFim = $('#dataFim').val();

        $.ajax({
            type: "GET",
            datatype: 'json',
            url: "{{ route('auditoria.displayDatatable') }}",
            data: {
                cpf: cpf,
                operacao: operacao,
                instituicao: instituicao,
                dataInicio: dataInicio,
                dataFim: dataFim,
            },
            success: function (data) {
                createTable(data);
                if (data.data.length == 0) {
                    $('#corpoTabela').html(
                        "<tr><td colspan='6' style='text-align:center'> " +
                        "Nenhum usuario de acordo com o que foi filtrado" +
                        "<td></tr>"
                    );
                }
            },
        });
    });

<!-- Here is my function who display the table -->

function createTable(data) {
    table = '';
    console.log(data);
    for (var i = 0; i < data.data.length; i++) {
        table += "<tr>";
        table += "<td>" + data.data[i].user.nome + "</td>";
        table += "<td>" + data.data[i].user.cpf + "</td>";
        table += "<td>" + data.data[i].event + "</td>";
        table += "<td style='text-transform: capitalize'>" + data.data[i].auditable_type+ "</td>";
        table += "<td>" + moment(data.data[i].created_at).format('DD/MM/YYYY hh:mm') + "</td>";
        table += "<td>" + moment(data.data[i].updated_at).format('DD/MM/YYYY hh:mm') + "</td>";
        table += "<td><a class='btn btn-primary btn-xs' href=\"/show/" + data.data[i].id + "\"> Ver </a>";
        table += "</tr>";
    }
    ;
    $('#corpoTabela').html(table);
};

我想要一种方法来分页我的json。为此,可以使用javascript,jquery,vue.js或Laravel的分页方法。请记住:过滤器可以单独使用,也可以同时使用。

1 个答案:

答案 0 :(得分:1)

您有两种选择。

1:通过进行更复杂的查询来重写代码,但返回按数据库过滤的结果,并且您的分页方法不会影响您的结果

2:使用LengthAwarePaginator类并手动创建分页。