Laravel Ajax Pagination for Collection, Query Builder, Complex SQL Query Result


Let’s say that you have an array of data which is a results from a complex Query Builder execution or from an Stored Procedure call, and you want to paginate them. 

Laravel provides pagination for Eloquent results out of the box, but for custom query result we need to do the pagination manually.

Let see how in the next example:

<?php namespace App\Http\Controllers;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class MemberController extends Controller {

    public function search(Request $request)
    {       
        $queryResults = [
            'item1',
            'item2',
            'item3',
            'item4',
            'item5',
            'item6',
            'item7',
            'item8',
            'item9',
            'item10'
            ];

        //Get current page form url e.g. &page=6
        $currentPage = LengthAwarePaginator::resolveCurrentPage();

        //Create a new Laravel collection from the array data
        $collection = new Collection($queryResults);

        //Define how many items we want to be visible in each page
        $perPage = 5;

        //Slice the collection to get the items to display in current page
        $currentPageSearchResults = $collection->slice(($currentPage - 1) * $perPage, $perPage)->all();

        //Create our paginator and pass it to the view
        $paginatedSearchResults= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
        $paginatedSearchResults->setPath($request->url());
        $paginatedSearchResults->appends($request->except(['page']));

        return view('search', ['results' => $paginatedSearchResults]);
    }
?>

Now in your Laravel view template add the following blade syntax:

 @foreach ($results as $result)
        <p>{{ $result }}</p>
 @endforeach

 <?php echo $results->render(); ?>

Now add the following Javascript to make the pagination to work on Ajax request instead of Page loading,

$(document).on('click', '.pagination a', function (e) {
                e.preventDefault();
                var url = $(this).attr('href');
                getItems(url);
                //window.history.pushState("", "", url);

            });
            function getItems(url) {
                $.ajax({
                    url : url,
                    dataType: 'json',
                    beforeSend:   function(){
                        AppCommonFunction.ShowWaitBlock();
                    }
                }).done(function (data) {
                    AppCommonFunction.HideWaitBlock();
                    $("#calendar-body").html(data.Content);
                }).fail(function (data) {
                    AppCommonFunction.HideWaitBlock();
                    if(data.responseJSON){
                        var errors = data.responseJSON;

                        errorsHtml = '<ul>';
                        $.each( errors , function( key, value ) {
                            errorsHtml += '<li>' + value[0] + '</li>';
                        });

                        errorsHtml += '</ul>';

                      alert(errorsHtml);
                    }else{                      
                        alert(data.responseText);
                    }
                });
            }


Written by Akram Wahid 7 years ago

are you looking for a chief cook who can well craft laravel and vuejs, to make some awsome butterscotch,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in

Responses

Be the first one to write a response :(

{{ item.member.name }} - {{ item.created_at_human_readable }}

{{ reply.member.name }} - {{ reply.created_at_human_readable }}