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 = [

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

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

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

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

 <?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) {
                var url = $(this).attr('href');
                //window.history.pushState("", "", url);

            function getItems(url) {
                    url : url,
                    dataType: 'json',
                    beforeSend:   function(){
                }).done(function (data) {
                }).fail(function (data) {
                        var errors = data.responseJSON;

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

                        errorsHtml += '</ul>';


Written by Akram Wahid 6 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


Be the first one to write a response :(

{{ }} - {{ item.created_at_human_readable }}

{{ }} - {{ reply.created_at_human_readable }}