Laravel 5 Pagination without "refresh"?

Asked

Viewed 741 times

0

I have a form where I display a table with data to assist the employee in creating the contract, this table is being paged:

($seguranças = DB::table('Segurança')
                 ->where('disponibilidade', '=', 'disponível')
                 ->orderBy('name', 'asc')
                 ->Paginate(15);))

When clicking on the pagination, rendering to the other pages all the data already filled in form are erased, how can I solve this problem?

  • which exact version of laravel?

  • want to do paging without refresh, with ajax? (that’s it???)

1 answer

1

You can use the dataTables.

However, there is an abstraction of the same for the.

I will write a tutorial on how I implemented it very simply and quickly, but without addressing all the technical aspects.

However, there are others more correct forms to do in the documentation, just consult.

Follow the project on Github https://github.com/yajra/laravel-datatables

Follow the documentation link https://yajrabox.com/docs/laravel-datatables

Follow the Datatables documentation link https://datatables.net/

Obs: At this very moment that I am writing the tutorial, I identified that the documentation site is off the air.

Come on.

Follow the installation procedures described on github, then follow the steps below:

In the archive Routes/web.php add the following route:

Route::get('/pagina/listar', 'ControllerAqui@listar')->name('listar');

She will be responsible for retrieve the data that will be displayed in the table.

Then go to your controller and implement a Métodlike this:

public function listar(Request $request)
{   
    // Consulta os dados a serem exibidos
    $query = PersonModel::select(['id','name', 'cpf', 'rg', 'phone']);
    // Monta os dados de acordo com o datatable
    $datatable =  Datatables::of($query);

    /**
    *
    * Retorna os dados no formato 
    * requisitado pelo datatable e 
    * impede o envio da coluna action
    * para a tabela.
    *
    * Isso porque a coluna action,
    * não possui dados, e sim os botões 
    * de ação editar e excluir. 
    **/
    return $datatable->blacklist(['action'])->make(true);
}

This already ensures that a json is returned when accessing the defined route.

After that, create a view with the following content

@extends('layouts.admin')
@section('page-title','Pessoas')
@section('content')
    <table id="people-table" class="col-md-12 table table-striped table-bordered">
        <thead>
            <tr>
            <th>Nome</th>
            <th>CPF</th>
            <th>RG</th>
            <th>Telefone</th>
            <th width="17%">Ação</th>
        </tr>
    </thead>
</table>
@endsection

<script>
/** 
* Exibe confirmação de exclusão ao clicar no botão excluir 
* O metodo confirmation() é de um componente do bootstrap
* chamado bootstrap confirmation
**/
$('table tbody').on('click','a[id^="person-delete"]', function (e) {
    e.preventDefault();
    $(this).confirmation('show');
});

/**
* o atributo "processing" define que os dados
* da tabela poderá serão processados a cada
* requisição.
* 
* O atributo "serverSide" informa que a tabela 
* fará requisições no servidor para consultar 
* novos dados.
* 
* O atributo "ajax" define para qual rota 
* fará a requisição. Esta rota é a que contém
* o json com os dados consultados pelo model. 
*
* O atributo columns é um array com todas as colunas 
* e seus respectivos valores consultados no banco.
*
* data: 'name' é o nome da coluna na tabela
* name: 'name' é o nome do campo vindo da consulta e seu valor.
*
* O campo "action" é responsável pela criação dos botões 
* de editar e excluir a linha da tabela.
*
**/
var table = $('#people-table').DataTable({
    destroy: true,
    lengthMenu: [ 5, 10, 15, 25, 50, 100, 'Todas' ],
    responsive: true,
    processing: true,
    serverSide: true,
    ajax: "{!! route('listar') !!}",
    columns: [
        {data: 'name', name: 'name'},
        {data: 'cpf', name: 'cpf'},
        {data: 'rg', name: 'rg'},
        {data: 'phone', name: 'phone'},
        {
            "data": "action",
            "render": function(data, type, row, meta){
                return '<a href="'+ $('link[rel="base"]').attr('href') + '/editar/' + row.id +'" class="btn btn-xs btn-info" title="Editar Pessoa"> <i class="fa fa-edit"></i></a> <a href="'+ $('link[rel="base"]').attr('href') + '/excluir/' + row.id +'" id="person-'+ row.id +'" class="btn btn-xs btn-danger" data-toggle="confirmation" data-btn-ok-label="Sim" data-btn-ok-class="btn-success" data-btn-ok-icon-class="material-icons" data-btn-ok-icon-content="" data-btn-cancel-label="Não" data-btn-cancel-class="btn-danger" data-btn-cancel-icon-class="material-icons" data-btn-cancel-icon-content="" data-title="Tem certeza que deseja excluir o cadastro de '+ row.name +'?" data-content="Esta ação não poderá ser desfeita." title="Excluir Pessoa"> <i class="fa fa-trash"></i></a>';
            }
        }
        ],
    });
</script>

If you want customize even more your table, just refer to documentation of dataTables and the documentation of abstraction created for the Larable.

Signal if you can make it work or not!

Success!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.