How to implement infinite ajax scroll pagination in Laravel? (ok)

https://www.itsolutionstuff.com/post/how-to-implement-infinite-ajax-scroll-pagination-in-laravel-5example.html

ok

C:\xampp\htdocs\reset\database\migrations\2022_05_17_095304_create_posts_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('posts', function (Blueprint $table) {
      $table->id();
      $table->string('title');
      $table->text('description');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('posts');
  }
}

C:\xampp\htdocs\reset\app\Models\Post.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
  use HasFactory;
  public $fillable = ['title', 'description'];
}

C:\xampp\htdocs\reset\database\factories\PostFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory {
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'title'       => $this->faker->text(10),
      'description' => $this->faker->text(150),
    ];
  }
}

C:\xampp\htdocs\reset\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller {
  public function myPost(Request $request) {
    $posts = Post::paginate(5);
    if ($request->ajax()) {
      $view = view('data', compact('posts'))->render();
      return response()->json(['html' => $view]);
    }
    return view('my-post', compact('posts'));
  }
}

C:\xampp\htdocs\reset\resources\views\my-post.blade.php

<!DOCTYPE html>
<html>
	<head>
		<title>Laravel infinite scroll pagination</title>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
		<style type="text/css">
			.ajax-load {
				background: #e1e1e1;
				padding: 10px 0px;
				width: 100%;
			}
		</style>
	</head>
	<body>
		<div class="container">
			<h2 class="text-center">Laravel infinite scroll pagination</h2>
			<br />
			<div class="col-md-12" id="post-data"> @include('data') </div>
		</div>
		<div class="ajax-load text-center" style="display:none">
			<p><img src="https://i.gifer.com/origin/34/34338d26023e5515f6cc8969aa027bca_w200.gif">Loading More post</p>
		</div>
		<script type="text/javascript">
			var page = 1;
			$(window).scroll(function() {
				if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
					page++;
					loadMoreData(page);
				}
			});
			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 records found");
						return;
					}
					$('.ajax-load').hide();
					$("#post-data").append(data.html);
				}).fail(function(jqXHR, ajaxOptions, thrownError) {
					alert('server not responding...');
				});
			}
		</script>
	</body>
</html>

C:\xampp\htdocs\reset\database\seeders\DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();
        \App\Models\Post::factory(100)->create();
    }
}

C:\xampp\htdocs\reset\resources\views\data.blade.php

@foreach($posts as $post)
<div>
	<h3><a href="">{{ $post->title }}</a></h3>
	<p>{{ $post->description }}</p>
	<div class="text-right">
		<button class="btn btn-success">Read More</button>
	</div>
	<hr style="margin-top:5px;">
</div>
@endforeach

C:\xampp\htdocs\reset\routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});
Route::get('my-post', [PostController::class,'myPost']);

How to implement infinite ajax scroll pagination in Laravel?

So, Today, i going to give you simple example of infinite scroll using jquery ajax on page scroll in laravel 6, laravel 7, laravel 8 and laravel 9 application from scratch. I use jquery scroll event for page scroll. this example is pretty simple, you can customize simply for your development.

You have to just follow bellow few step and you will get infinite scroll in your laravel application. After finish all those step you will be find output as like bellow preview:

Preview:

Step 1: Add Table and Model

we require to create new table "posts" that way we will get data from this table, you can use your own table but this is for example. we have to create migration for posts table using Laravel 5 php artisan command, so first fire bellow command:

php artisan make:migration create_post_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create posts table.

use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreatePostTable extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('posts', function (Blueprint $table) {            $table->increments('id');            $table->string('title');            $table->text('description');            $table->timestamps();        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::drop("posts");    }}

Ok, now we have to run migration using laravel artisan command:

php artisan migrate

Now, we require to create table model for posts table, so fist create new Post.php in your app directory as like bellow:

app/Post.php

namespace App;use Illuminate\Database\Eloquent\Model;class Post extends Model{    public $fillable = ['title','description'];   }

Step 2: Add Route

In this is step we need to add route for generate view. so open your app/Http/routes.php file and add following route.

Route::get('my-post', 'PostController@myPost');

Read Also: PHP - File upload progress bar with percentage using form jquery example

Step 3: Create Controller

If you haven't PostController then we should create new controller as PostController in this path app/Http/Controllers/PostController.php. Make sure you should have posts table with some data. this controller will manage data and view file, so put bellow content in controller file:

app/Http/Controllers/PostController.php

namespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Requests;use App\Post;class PostController extends Controller{    public function myPost(Request $request)    {    	$posts = Post::paginate(5);    	if ($request->ajax()) {    		$view = view('data',compact('posts'))->render();            return response()->json(['html'=>$view]);        }    	return view('my-post',compact('posts'));    }}

Step 4: Create View Files

In last step, we have to create view two file "my-post.blade.php" for main view and another for data, so first create my-post.blade.php file:

resources/view/my-post.php

<!DOCTYPE html><html><head>	<title>Laravel infinite scroll pagination</title>	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">  	<style type="text/css">  		.ajax-load{  			background: #e1e1e1;		    padding: 10px 0px;		    width: 100%;  		}  	</style></head><body><div class="container">	<h2 class="text-center">Laravel infinite scroll pagination</h2>	<br/>	<div class="col-md-12" id="post-data">		@include('data')	</div></div><div class="ajax-load text-center" style="display:none">	<p><img src="http://demo.itsolutionstuff.com/plugin/loader.gif">Loading More post</p></div><script type="text/javascript">	var page = 1;	$(window).scroll(function() {	    if($(window).scrollTop() + $(window).height() >= $(document).height()) {	        page++;	        loadMoreData(page);	    }	});	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 records found");	                return;	            }	            $('.ajax-load').hide();	            $("#post-data").append(data.html);	        })	        .fail(function(jqXHR, ajaxOptions, thrownError)	        {	              alert('server not responding...');	        });	}</script></body></html>

resources/view/data.php

Read Also: Laravel Dynamic Dependent Dropdown Example

@foreach($posts as $post)<div>	<h3><a href="">{{ $post->title }}</a></h3>	<p>{{ str_limit($post->description, 400) }}</p>	<div class="text-right">		<button class="btn btn-success">Read More</button>	</div>	<hr style="margin-top:5px;"></div>@endforeach

Ok, now you can check and test.....

Last updated