infinite scroll pagination in laravel

How to create infinite scroll pagination in laravel 8 ?

In this tutorial, I will give you an example of Infinite Scroll Pagination, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application, Sometimes we need to use load more or see more data pagination in Blade file according to project or client requirement in laravel application.


Infinite Scroll Pagination :

You must have seen this type of pagination in Social Sites, Ecommerce Websites, when we scroll down, the data rendered in every scroll, and the Data update in every scroll.

Infinite Scroll Pagination mostly works in a load more or see more Buttons, when we click on these buttons you must have seen data is updated from time to time with the help of Javascript and AJAX.


Generating Migration :

php artisan make:migration create_infinite_scroll_examples_table


Migration Structures :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateInfiniteScrollExamplesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('infinite_scroll_examples', function (Blueprint $table) {
            $table->id();
            $table->string('post_author');
            $table->string('post_title');
            $table->string('post_description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('infinite_scroll_examples');
    }
}


Run Migration :

php artisan:migrate
infinite scroll pagination in laravel


Make Model :

php artisan make:model Model/InfiniteScroll

app\Model\InfiniteScroll.php

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class InfiniteScroll extends Model
{
     protected $table = 'infinite_scroll_examples';
}


Generate Dummy Data Using Seeder-Faker :

Laravel makes it pretty easy to perform seeding , a seeder class contains a run method by default. You can insert data by using a query builder or Eloquent model factories

Recommended Article: Database seeder in Laravel.

database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
    	$faker = Faker::create();
    	foreach(range(1,100) as $index)
    	{
    		DB::table('infinite_scroll_examples')->insert([
    			'post_author' => $faker->text(40),
    			'post_title'  => $faker->text(40),
    			'post_description' => $faker->text(200),
    		]);
    	}
        // $this->call(UsersTableSeeder::class);
    }
}


Run Seeder :

php artisan db:seed

After successfully running the seed command in a terminal, we have 100 records in our infinite_scroll_examples table in the Database.

infinite scroll pagination in laravel
infinite scroll pagination in laravel
infinite scroll pagination in laravel
infinite scroll pagination in laravel
infinite scroll pagination in laravel

routes\web.php

#Load more Infinite Scroll in Laravel
Route::get('/load-more-data-example','ProductController@InfiniteScrollDataList');

Controller

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Model\InfiniteScroll;

class ProductController extends Controller
{ 
public function InfiniteScrollDataList(Request $request)
    {
        $posts =  InfiniteScroll::paginate(5);
        if($request->ajax()){
            $view = view('data',compact('posts'))->render();
            return response()->json(['html'=>$view]);
        }
        return view('autoLoadexample',compact('posts'));
    }
}

Blade Files

Now, we have to create two-blade files autoLoadexample for the main view and another for data, so first create an autoLoadexample.blade.php file.

Don’t forget to include the data.blade.php file in the autoLoadExample.blade.php file.

resources/views/autoLoadExample.blade.php

Write JavaScript for load more content while page scrolling in Laravel blade file.

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Post List Data</title>
       <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <section>
      <div class="container">
        <div class="row">
         <div class="col-md-12">
            <h2 class="text-center">Infinite | Load more Pagnination Example</h2>
      </div>
      <div class="col-md-12" id="post-data">
         @include('data')
      </div>
   </div>
</div>
</section>
<div class="ajax-load text-center" style="display:none">
   <p><img src="{{asset('img/loaderImg.gif')}}">Load More Post...</p>
</div>
   </body>
</html>

<script>
   function loadMoreData(page)
   {
      $.ajax({
         url:'?page=' + page,
         type:'get',
         beforeSend: function()
         {
            $(".ajax-load").show();
         }
      })
      .done(function(data){
         if(data.html == ""){
            $('.ajax-load').html("No more Posts Found!");
            return;
         }
         $('.ajax-load').hide();
         $("#post-data").append(data.html);
      })
      // Call back function
      .fail(function(jqXHR,ajaxOptions,thrownError){
         alert("Server not responding.....");
      });

   }
   //function for Scroll Event
   var page =1;
   $(window).scroll(function(){
      if($(window).scrollTop() + $(window).height() >= $(document).height()){
         page++;
         loadMoreData(page);
      }
   });
   </script>

resources/views/data.blade.php

In the data.blade.php file, we display all posts using foreach loop, and after that, we include in this file in autoLoadExample Blade file, where we already write javascript or ajax for scrolling down and rendering more posts using a gif loader.

@foreach($posts as $post)
<div class="card" style="margin-bottom:20px;">
	<div class="card-header">
		<h3><a href="#">{{ $post->post_title}}</a></h3>
	</div>
	<div class="card-body">
		<p>{{$post->post_description}}</p>
		<div class="text-center">
			<button type="button" class="btn btn-success">Read More</button>
		</div>
	</div>
</div>
@endforeach

Finally, we paginated the App\Model\InfiniteScroll model and indicate that we plan to display 5 records per screen. As you can see below the given images.

infinite scroll pagination in laravel
infinite scroll pagination in laravel
infinite scroll pagination in laravel
infinite scroll pagination in laravel


In this article, we learned “infinite scroll pagination in laravel or Load More Content While Page Scrolling pagination in laravel”, I hope this article will help you with your Laravel application Project.

Read Also : Custom Pagination in Laravel.