Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel Auto Load Infinite Scroll pagination with search

Laravel Auto Load Infinite Scroll pagination with search

Aman Jain, May 8, 2022May 8, 2022

In this tutorial we will learn Auto Load Infinite Scroll pagination with search in Laravel using Ajax jQuery. Laravel provides its own library to build the pagination html, which we can easily use in our html page using $model->links() method and $model->paginate() method to make a long list into pagination.In some cases we want to give a better user experience to users to load the next page without their interaction means load the next data on scroll of page. Infinite Scroll gives flexibility to user load the more data without clicking on any pagination link and will append the data, Thus in this tutorial i will show you to use the existing Laravel pagination data with infinite scroll using jQuery Ajax.

In this example i will use bootstrap to show better UI with pagination, jQuery to execute Ajax and Laravel pagination to show pagination.

We will create simple controller , two views, models and jQuery.

So, let’s begin the tutorial

Step 1: Create a laravel project

First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel example-app

Step 2: Configure database

Next step is to configure the database for our project, table and data. So open .env or if file not exist then rename .env.example file to .env file in root folder and change below details

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create Model, Migration and Seeders

If you have table and large data already then you can skip this step but if you are beginner and trying to implement pagination then pagination required model, large dataset in table so in this step we are creating a model and migration using artisan command

php artisan make:model Article -m

Above command will create two files one is migration and other one is model. open migration file which is located at database/migrations/timestamp_create_articles_table.php and edit the schema as below

  public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body');
            $table->timestamps();
        });
    }

Run migration using artisan command in command line

php artisan migrate

Output of above command

Migrating: 2021_11_27_112800_create_articles_table
Migrated:  2021_11_27_112800_create_articles_table (45.63ms)

Now create seeder in database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();

    	for ($i=0;$i<=100;$i++) {
            DB::table('articles')->insert([
                'title' => $faker->name,
                'body' => $faker->text,
                'email' => $faker->email,
                'updated_at' =>$faker->datetime,
                'created_at' => $faker->datetime              
            ]);
        }
        
    }
}

Run Seeder in command line

php artisan db:seed

Step 4 : Create a controller

Create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller ArticleController

Now, add the controller logic for pagination and Ajax

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;


class ArticleController extends Controller
{
    public function infiniteScrollAjaxPagination(Request $request)
    {
       $articles=Article::when($request->has("title"),function($q)use($request){
            return $q->where("title","like","%".$request->get("title")."%");
        })->paginate(5);
        if($request->ajax()){
            return view('articles.article-infinite-pagination',['articles'=>$articles]); 
        } 
        return view('articles.article-infinite-scroll',['articles'=>$articles]);
    }
}

Here, i used Article model to paginate the data and $request->ajax() method to check if request is Ajax then response with articles.article-infinite-pagination partial page otherwise with full page.

Step 5 : Create the views

Create two views one for full page and other for list with pagination therefore creating views in resource/articles/article-infinite-scroll.blade.php and resource/articles/article-infinite-pagination.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Readerstacks Laravel Auto Load Infinite Scroll pagination with search </title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

</head>

<body class="antialiased">
  <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-12 ">
            <h3>Laravel Auto Load Infinite Scroll pagination with search - Readerstacks</h3>
            <div id="search">

              <form id="searchform" name="searchform">
                <div class="form-group">
                  <label>Search by Title</label>
                  <input type="text" name="title" value="{{request()->get('title','')}}" class="form-control" />


                </div>
                <div class="form-group">
                  <label>Search by body</label>
                  <input type="text" name="body" value="{{request()->get('body','')}}" class="form-control" />


                </div>
                <button class='btn btn-success'>Search</button>
              </form>


            </div>

            <div id="pagination_data" class="row">

              @include("articles.article-infinite-pagination",['articles'=>$articles])

            </div>

            <div id="loader" style="display:none !important" class='d-flex justify-content-center'>Loading...</div>


          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">Laravel Auto Load Infinite Scroll pagination with search
        </a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>

</body>
<script>
  $(function() {
    var page = 1;
    var loading = false;
    var loadMore = function() {
      page = page + 1;
      var url = "{{url('infinite-scroll-example')}}?" + $("#searchform").serialize();
      var append = url.indexOf("?") == -1 ? "?" : "&";
      var finalURL = url + append + "page=" + page;


      //set to current url
      window.history.pushState({}, null, url);
      loading = true;
      $("#loader").show();
      $.get(finalURL, function(data) {
        if (data == "") {

          $("#loader").html("!No more data to show");
        } else {
          $("#pagination_data").append(data);
          loading = false;
          $("#loader").hide();
        }

      });
    }

    $(document).on("submit", "#searchform", function() {
      page = 0;
      $("#pagination_data").html("");
      loadMore();
      return false;
    });

    var subscribeOnScroll = function() {

      $(window).scroll(function() {
        console.log($(window).scrollTop(), $(document).height() - $(window).height())
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10 && loading == false) {
          loadMore();
        }
      });

    }
    subscribeOnScroll();
 
  });
</script>

</html>

As we can see i added bootstrap and jQuery as well. We also include @include("articles.article-infinite-pagination",["article"=>$article]) so we can show article on first render.

And resources/views/articles/article-infinite-pagination.blade.php

@foreach($articles as $article)
<div class='col-sm-4'>
  <div class="card" style="width: 18rem;margin:5px;">
    <img class="card-img-top" src="https://i0.wp.com/readerstacks.com/wp-content/uploads/2021/11/Laravel-Ajax-pagination-example-with-search.png?w=850&ssl=1" alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">{{$article->title}}</h5>
      <h6>{{$article->created_at}}</h6>
      <p class="card-text">{{substr($article->body,0,50)}}</p>
      <a href="#" class="btn btn-primary">Go somewhere</a>
    </div>
  </div>
</div>

@endforeach

Then we have jQuery to handle the pagination and search

$(function() {
    var page = 1;
    var loading = false;
    var loadMore = function() {
      page = page + 1;
      var url = "{{url('infinite-scroll-example')}}?" + $("#searchform").serialize();
      var append = url.indexOf("?") == -1 ? "?" : "&";
      var finalURL = url + append + "page=" + page;


      //set to current url
      window.history.pushState({}, null, url);
      loading = true;
      $("#loader").show();
      $.get(finalURL, function(data) {
        if (data == "") {

          $("#loader").html("!No more data to show");
        } else {
          $("#pagination_data").append(data);
          loading = false;
          $("#loader").hide();
        }

      });
    }

    $(document).on("submit", "#searchform", function() {
      page = 0;
      $("#pagination_data").html("");
      loadMore();
      return false;
    });

    var subscribeOnScroll = function() {

      $(window).scroll(function() {
        console.log($(window).scrollTop(), $(document).height() - $(window).height())
         //-10 here to tell system to load data before 10px distance 
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10 && loading == false) {
          loadMore();
        }
      });

    }
    subscribeOnScroll();
 
  });

Load more –
This is the main part, we created subscribeOnScroll and subscribed for on scroll event of window. If we are at bottom of the page then loadMore function will call and ajax will hit the server to fetch the data.

var subscribeOnScroll = function() {

      $(window).scroll(function() {
        console.log($(window).scrollTop(), $(document).height() - $(window).height())
         //-10 here to tell system to load data before 10px distance 
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10 && loading == false) {
          loadMore();
        }
      });
}

Load Before Reach to End

-10 we use to tell the system to hit the load more data before hit the end of the scroll so that means for example if window height is 600px then our data will load on 590px before reaching to the end.

 if ($(window).scrollTop() >= 
     $(document).height() - $(window).height() - 10 && loading == false) {
          loadMore();
}

Search

For search we have created a event of jQuery to handle the search and reset the pagination from 1

 $(document).on("submit", "#searchform", function() {
      page = 0;
      $("#pagination_data").html("");
      loadMore();
      return false;
 });

Step 6 : Create Routes

Second step is to create the routes to show the view and submit the form

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\ArticleController;


Route::get('/articles',[ArticleController::class, 'infiniteScrollAjaxPagination']); 

Run and final output:

Screenshot 2022 05 08 at 1.28.02 PM
Screenshot 2022 05 08 at 1.28.17 PM
Screenshot 2022 05 08 at 12.18.37 PM
Laravel 8 infinite scroll Ajax pagination with search

Also Read : Laravel Ajax pagination with search

Related

Php Laravel Laravel 9 ajaxbootstrapinfinite scrolljquerylaravelpaginationphp

Post navigation

Previous post
Next post

Related Posts

Laravel validate checkbox in laravel

How to validate checkbox in laravel ?

January 26, 2024March 16, 2024

Certainly! Below is a step-by-step guide on how to validate checkbox in Laravel application. Let’s assume you are working on a form that includes checkbox and you want to make sure that at least one checkbox is selected before the form is submitted. We will take a simple example as…

Read More
Php How to Filter Data Using Relational Model in Laravel

How to Filter Data Using Relational Model in Laravel ?

June 29, 2022July 1, 2022

In this article i will show you to filter data using the relational model in laravel. Using the laravel relationship between the models we can easily fetch relative data but sometimes we want to fetch the data by filtering the child model that affect the result of parent model. You…

Read More
Php How to create logs file in laravel

How to create logs file in laravel 8 / 9 ?

May 12, 2022May 12, 2022

In this article i will show you to use and create logs file in laravel. Logging is an important aspect when you want to debug your application or you want to monitor the user activities on the application. Laravel itself provides a robust library to create logging on daily basis,…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version