doutang6600 2017-07-20 21:31
浏览 119
已采纳

Laravel与ajax和json的分页

I have four fields who realize filters on my laravel model. I'm using ajax to take a response data from the from the template blade and return a json response. My function:

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

When I replace the get() method by paginate(10), for example, my responses who are filter() don't work.

My template blade is like this:

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

I want a way to paginate my json. For this can use javascript, jquery, vue.js, or the pagination methods from Laravel. Just keep in mind: the filters can be used independently or simultaneously.

  • 写回答

1条回答 默认 最新

  • dongxie2756 2017-07-21 00:35
    关注

    You have two options.

    1: rewrite your code by making more complicated query, but returning results filtered by database, and your paginate method won't affect your results

    2: use LengthAwarePaginator class and create pagination manually.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退