Asynchronous pagination with laravel

2

I made a simple pagination with laravel using the ->paginate() return, but as you know, it's not an asynchronous action, which leaves bad paging.

I found some examples, but I could not make it work. Does anyone have tips?

    
asked by anonymous 07.12.2016 / 13:36

1 answer

3

Using $.post of and paginate() of the has an easy way to work with ajax :

Example:

Table

  

Theparquetablehastwofieldsidanddescription

ModelParque

<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classParqueextendsModel{protected$fillable=array('description');protected$table='parque';public$timestamps=false;}

Routes

Route::get('pagina',['as'=>'pagina.get','uses'=>'PaginasController@index']);Route::post('pagina',['as'=>'pagina.post','uses'=>'PaginasController@post']);

ControllerPaginasController

<?phpnamespaceApp\Http\Controllers;useApp\Models\Parque;useIlluminate\Http\Request;classPaginasControllerextendsController{publicfunctionindex(){returnview('parques');}publicfunctionpost(){$data=['data'=>Parque::orderBy('description')->paginate(5)];returnview('table',$data);}}

Home(fileparques.blade.php)

<!DOCTYPEhtml><htmllang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="/js/jquery-2.2.4.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
    <link href="/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel</title>
</head>
<body>
<div id="table"></div>
<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    function getTable(url)
    {
        if (url == '') url = "{{route('pagina.post')}}";
        $.post(url, null, function(data)
        {
            $('#table').html(data);
            linkAjax();
        },'html');
    }
    function linkAjax()
    {
        $items = $('#table table').find('[href]');
        $.each($items, function(index, element){
            var href = $(element).attr('href');
            $(element).attr('href', 'javascript:getTable("' + href + '")');
        });
    }
    $(document).ready(function(){
        getTable('');
    });
</script>
</body>
</html>

Excerpt of table to be loaded via ajax (file table.blade.php ):

<table class="table">
    <tr>
        <th style="width: 20%">Id</th>
        <th>Descrição</th>
    </tr>
    @foreach($data as $v)
    <tr>
        <td>{{$v->id}}</td>
        <td>{{$v->description}}</td>
    </tr>
    @endforeach
    <tr>
        <td colspan="2" valign="center" align="center">
            {{ $data->links() }}
        </td>
    </tr>
</table>
This is an example that should be adapted to your project, due to lack of information, I could not reflect a real, but functional, example.     
07.12.2016 / 19:54