Create load more pagination with ajax in laravel | Laravel Tutorials

create-load-more-ajax-pagination-in-laravel-5

Hello World, Today i am going to create load more pagination with ajax in laravel. In this tutorial, we will create a product list example in which we will show product list with load more button. When we will click on the load more button the more products will load at the bottom of current list without reloading the page. If all products has been loaded then load more button will hide. So lets start this tutorial.

I have divided this tutorials into followings steps:

  • Create product model and migration
  • Table schema setting for product data
  • Generate dummy data for products
  • Create Product Controller
  • Routes Setting
  • Create product list template to show default products
  • Implement load more pagination code
  • Route Setting
  • Product Controller Setting
  • Run the example application


Here, I have assumed that you have basic knowledge of laravel 5. If not then please follow my laravel tutorials.

In this tutorial, I have implement ajax pagination with jquery ajax functionality.


Create product model and migration

In this step, we will create model and migration for product with artisan command.
Enter the following command to create product model and migration.

php artisan make:model -m

Here __-m__ flag will create migration file in /database/migrations/…product_table.php


Table schema setting for product data

  • Open new created products migration file and the replace the __up__ method code with the following code.
Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->mediumText('summery');
            $table->string('image');
            $table->tinyInteger('price');
            $table->timestamps();
        });
  • Run the migrate command
php artisan migrate

Generate dummy data for products

In this step, we will generate dummy data for products. This is my favorite thing in laravel 🙂

  • Create imgs folder in /public folder. Here we will save generate product images.
  • Open /database/factory/UserFactory.php and add the following code in the end of this file.
  • Open command line and go to this project folder and then enter the following commands to generate dummy data.
>> php artisan tinker
>> factory(App\Product::class,24)->create();

Create Product Controller

  • Enter the following command to create ProductController
>> php artisan make:controller ProductController

In this newly created controller, Add the following index method code.

//  Home Page
    function index(){
        $products=Product::take(6)->get();
        return view('load-more-data.load-more',['products'=>$products]);
    }

Routes Setting

  • Open /routes/web.php and add the following code for showing default product list.
  • // Load More Data
    Route::get('load-more','ProductController@index');

Create product list template to show default products

In this step, we will create product list template. In this template, we will show default products. For designing, we have implemented bootstrap 4 css.

  • Create /resources/views/load-more-data/load-more.blade.php file and add the following code in it.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Load more data with ajax in laravel</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
</head>
<body>
    <div class="container mt-4">
        <h3 class="mb-4 border-bottom pb-1">Product List</h3>
        <div class="row product-list">
            @if(count($products)>0)
                @foreach($products as $data)
                <div class="col-sm-4 mb-3 product-box">
                    <img src="{{ asset('imgs/'.$data->image) }}" class="card-img-top" alt="{{ $data->title }}" />
                    <div class="card">
                        <div class="card-body">
                        <h5 class="card-title">{{ $data->id }}. {{ $data->title }}</h5>
                        <p class="card-text">{{ str_limit($data->summery,20) }}</p>
                        Price: <span class="badge badge-secondary">$ {{ $data->price }}</span>
                        </div>
                    </div>
                </div>
                @endforeach
            @endif
        </div>
    @if(count($products)>0)
    <p class="text-center mt-4 mb-5"><button class="load-more btn btn-dark" data-totalResult="{{ App\Product::count() }}">Load More</button></p>
    @endif
    </div>
</body>
</html>

Implement load more script for pagination

In this step, we will implement jquery ajax pagination. When user will click on the load more button then next 6 (limit) product will append at the bottom. If product list ends then load more button will hide.

  • Add the following code in load-more template after Container div.
{{-- Ajax Script Start --}}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
    var main_site="{{ url('/') }}";
</script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".load-more").on('click',function(){
            var _totalCurrentResult=$(".product-box").length;
            // Ajax Reuqest
            $.ajax({
                url:main_site+'/load-more-data',
                type:'get',
                dataType:'json',
                data:{
                    skip:_totalCurrentResult
                },
                beforeSend:function(){
                    $(".load-more").html('Loading...');
                },
                success:function(response){
                    var _html='';
                    var image="{{ asset('imgs') }}/";
                    $.each(response,function(index,value){
                        _html+='<div class="col-sm-4 mb-3 product-box">';
                            _html+='<img src="'+image+value.image+'" class="card-img-top" alt="'+value.title+'" />';
                            _html+='<div class="card">';
                                _html+='<div class="card-body">';
                                    _html+='<h5 class="card-title">'+value.id+'. '+value.title+'</h5>';
                                    _html+='<p class="card-text">'+value.summer+'</p>';
                                    _html+='Price: <span class="badge badge-secondary">'+value.price+'</span>';
                                _html+='</div>';
                            _html+='</div>';
                        _html+='</div>';
                    });
                    $(".product-list").append(_html);
                    // Change Load More When No Further result
                    var _totalCurrentResult=$(".product-box").length;
                    var _totalResult=parseInt($(".load-more").attr('data-totalResult'));
                    console.log(_totalCurrentResult);
                    console.log(_totalResult);
                    if(_totalCurrentResult==_totalResult){
                        $(".load-more").remove();
                    }else{
                        $(".load-more").html('Load More');
                    }
                }
            });
        });
    });
</script>
{{-- Ajax Script End --}}

Route Setting for fetching data via ajax

  • Add the following code in /routes/web.php
// Ajax Data
Route::get('load-more-data','ProductController@more_data');

ProductController configuration for load more data

  • Add the following method, This method will return next (6) data in json format.
// Fetch More Data
    function more_data(Request $request){
        if($request->ajax()){
            $skip=$request->skip;
            $take=6;
            $products=Product::skip($skip)->take($take)->get();
            return response()->json($products);
        }else{
            return response()->json('Direct Access Not Allowed!!');
        }
    }

Run the example application

  • Open application in browser.
  • You will see the following screen.

create-load-more-ajax-pagination-in-laravel-5-screenshot

  • Click on the load button. You will see that more product has been loaded at the bottom.

I hope you are enjoying my tutorial. Please add your feedback in the comment section. Thank you 🙂 🙂

1 thought on “Create load more pagination with ajax in laravel | Laravel Tutorials”

Leave a Reply