Suppose you are going to load some users in your web application and you want to create an infinite scroll ajax pagination and your system is Laravel. But unfortunately, you do not know how to create a laravel 9 infinite scroll example. But do not worry cause in this example, we will see laravel infinite scroll pagination.

I will simply create users list to show you laravel 9 infinite scroll. To create this infinite scroll pagination in Laravel, I will use ajax request. So let's see laravel pagination ajax scroll tutorial.

Preview of Laravel Infinite Scroll Ajax Pagination

laravel-infinite-scroll-pagination-ajax

Step 1: Install Laravel

First of all, we need to get a fresh Laravel 9 version application using the bellow command, So open your terminal OR command prompt and run the bellow command to start laravel 9 infinite scroll example.

composer create-project laravel/laravel example-app

 

Step 2: Connect Database

After successfully installing the laravel app and then configuring the database setup. We will open the ".env" file and change the database name, username and password in the env file to create laravel pagination infinite scroll.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

 

Read also: Ajax Pagination With Search And Filter In Laravel

 

Step 3: Create Migration and Model

In this step, we need to create users table and model. then we need to run a migration. so let's change the files.

database/migrations/create_users_table.php

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('status')->nullable()->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

 

Now update the user model by replacing it with the below code:

app/Models/User.php

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
  
class User extends Authenticatable
{
    use HasFactory, Notifiable;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password'
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
  
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

 

Now you have to run this migration by following the command:

php artisan migrate

 

Now update the seeder class like below:

Database\Seeders\DatabaseSeeder.php

<?php

namespace Database\Seeders;

use App\Models\Post;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;

class DatabaseSeeder extends Seeder
{
    public function run()
    {   
        for ($i=0; $i < 100; $i++) { 
            User::create([
                'name' => fake()->name(),
                'email' => fake()->unique()->safeEmail(),
                'email_verified_at' => now(),
                'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
                'remember_token' => Str::random(10),
                'status' => $i % 2 === 0 ? 'active' : 'inactive'
            ]);
        }
    }
}

 

Now run the below command to insert some dummy data.

php artisan db:seed

 

Read also: Ajax Pagination With Search And Filter In Laravel

 

Step 4: Create Route

Here, we need to add one more route to display the users data with laravel infinite scroll. so let's add that route in the web.php file.

routes/web.php

<?php

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

/*
|--------------------------------------------------------------------------
| 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('/', [TutorialController::class,'index'])->name('pagination.fetch');

 

Step 5: Create Controller

Here, we need to add the index() method for fetching users data with infinite scroll laravel 9 in TutorialController. so let's add like as below:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

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

class TutorialController extends Controller
{   
    public function index(Request $request)
    {
    	$users = User::paginate(5);

    	if ($request->ajax()) {
    		$view = view('child',compact('users'))->render();
            return response()->json(['html'=>$view]);
        }

    	return view('welcome',compact('users'));
    }
}

 

Step 6: Create Blade file

In this step, we need to create a welcome blade file and update for user blade file. so let's change it.

resources/views/welcome.blade.php

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 9 Ajax infinite scroll pagination - Laravelia</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  	<style type="text/css">
  		.ajax-load{
  			background: #e1e1e1;
		    padding: 10px 0px;
		    width: 100%;
  		}
  	</style>
</head>
<body>

<div class="container">
	<h2 class="text-center">Laravel 9 Ajax infinite scroll pagination - Laravelia</h2>
	<br/>
	<div class="col-md-12" id="post-data">
		@include('child')
	</div>
</div>

<div class="ajax-load text-center" style="display:none">
	<p><img src="{{ asset('loading-waiting.gif') }}"></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 records!");
	                return;
	            }
	            $('.ajax-load').hide();
	            $("#post-data").append(data.html);
	        })
	}
</script>
</body>
</html>

 

Now create a child blade file and update it like this: 

resources/views/child.blade.php

@foreach($users as $user)
<div>
	<p><a href="">{{ $user->name }}</a></p>
    <p><a href="">{{ $user->email }}</a></p>
</div>
@endforeach

 

Read also: Laravel 9 Ajax Pagination With Next Previous Button

 

Ok, now we are ready to go and test laravel infinite scroll pagination tutorial. So let's run the project using this command:

php artisan serve

 

Now you can test our application by visiting the below URL:

URL
http://127.0.0.1:8000/

 

Conclusion

Now we know laravel 9 infinite scroll. Hope this laravel pagination ajax scroll will help you to create laravel 9 infinite scroll example.