The Load More or Show More functionality is very simple and user-friendly because not all data loads simultaneously. Instead, data will load as you scroll or click a button, similar to pagination but without page refresh. In this post, we will create this feature to load more data from a MySQL database using Ajax in Laravel Framework, leveraging Laravel lazy loading pagination techniques. Let's dive into the process of building scroll pagination in Laravel.

Laravel 11 Ajax -  Load More Data on Page Scroll in Laravel 11 using jQuery Ajax

Table Of Content

1 Prerequisites

1.) PHP version of >= 8.2
2.) Composer
3.) Mysql

2 Introduction

In this guide, we will create a posts table using migration. Then, we will develop a data model for the posts and a factory class to generate dummy post data. Lastly, we'll build a route to load posts dynamically and write the necessary code for auto-loading more data on page scroll using AJAX, integrating the power of Laravel lazy loading pagination and scroll pagination in Laravel.

3 Create / Install a Laravel Project

3.1 Install Laravel Project

First, ensure Composer is installed on your system. Use the following command to install a new Laravel Project:

composer create-project laravel/laravel laravel11-ajax-load-more-app

Navigate to your project directory:

cd laravel11-ajax-load-more-app

3.2 Configure MySql Database

Open the .env file and input the necessary database credentials:

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

4 Create Migration

Next, create a migration for the posts table using the Laravel artisan command:

    php artisan make:migration create_posts_table

In the migration file located at database/migrations, add the following code to define the posts table structure:
    
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description');
            $table->string('image');
            $table->timestamps();
        });
    }

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

Run the migration:

php artisan migrate

5 Create Model

Now, create the Post model for the posts table. Create the file at app/Models/Post.php and add the following code:
    
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'description',
        'image'
    ];
}



6 Create Factory Class

Generate a factory class to create dummy data that loads dynamically during scrolling:

php artisan make:factory PostFactory --model=Post

Update the database/factories/PostFactory.php with:
    
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'description' => fake()->text(),
            'image' => fake()->imageUrl(800,600),
            
        ];
    }
}

To generate 100 dummy records, use:

php artisan tinker


Post::factory()->count(100)->create()

7 Create Controller (PostController)

Create a controller to handle the data loading functionality:

php artisan make:controller PostController

In PostController.php, create an index function to implement the lazy loading pagination logic:

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

    }
}
?>

8 Create view (Blade)

In the resources/viewsdirectory, create posts.blade.php for the main view:
    
    <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Ajax Load More Data on Page Scroll in Laravel 11</title>
    <style>
        body {
            height: 1000px;
        }
    </style>
</head>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<body>
    <div class="container">
    <h1>Ajax Load More Data on Page Scroll using JQuery Laravel - getsamplecode.com</h1>
        <div id="data-wrapper" class="row">
            @include('data')
        </div>
        <div class="auto-load-message text-center" style="display: none;"> </div>
    </div>
</body>
<script>
    var ENDPOINT = "{{ route('posts.index') }}";
    var page = 1;
    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() >= ($(document).height() - 20)) {
            page++;
    LoadMoreData(page);
    }
});

    function LoadMoreData(page) {
        $.ajax({
                url: ENDPOINT + "?page=" + page,
                datatype: "html",
                type: "get",
                beforeSend: function () {
                    $('.auto-load-message').show();
                    $('.auto-load-message').html("Loading... ");
                }
            })
            .done(function (response) {
                if (response.html == '') {
                    $('.auto-load-message').html("We don't have more data to display ");
                    $('.load-more-data').hide();
                    return;
                }
                $("#data-wrapper").append(response.html);
            })
            .fail(function (jqXHR, ajaxOptions, thrownError) {
                console.log('Server error occured');
            });
    }
</script>
</body>
</html>

    
Create data.blade.php for the dynamic data:
    
    @foreach ($posts as $post)
<div class="col-sm-4 mb-3 product-box">
                            <img src="{!! $post->image !!}" class="card-img-top" alt="{{ $post->name }}" />
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">{{ $post->id }}  {{ $post->name }}</h5>
                                    <p class="card-text">{!! $post->description !!}</p>
                                </div>
                            </div>
                        </div>
@endforeach
    

9 Define Routes

In routes/web.php, define the necessary routes:

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

Route::get('/', function () {
    return view('welcome');
});
Route::get('posts',[PostController::class,'index'])->name('posts.index');

10 Folder Structure

11 Run Laravel Server to Test the App

Use the following command to serve the Laravel app:

php artisan serve

12 Conclusion

You have successfully implemented Load More Data on Page Scroll in Laravel 11 using jQuery Ajax, utilizing Laravel lazy loading pagination and scroll pagination techniques.

Tags