Load More Data in Laravel 11 using Ajax

In this article, you will learn how to Load More Data in Laravel 11 using jQuery Ajax. Here you will find how to dynamically autoload the data on infinite page scroll in Laravel application with the help of jQuery AJAX.

The Laravel load more button pagination will replace the Laravel pagination pattern with load more data on page scroll in Laravel using jQuery AJAX.

Laravel 11 Load More Data On Page Scroll

  • Step: 1 Install Laravel App
  • Step: 2 Setup Database Connection
  • Step: 3 Create Mode and Run Migration
  • Step: 4 Create Routes for Laravel load more jquery
  • Step: 5 Create Controller
  • Step: 6 Create Blade view files
  • Step: 7 Generate Dummy Data for Testing
  • Step: 8 Run the Development server and Test

#1 Install Laravel App

First, you just need to download or install a fresh Laravel application using the following command.

composer create-project --prefer-dist laravel/laravel laravel-autoload-pagination

Next, go into your installed app directory:

cd laravel-autoload-pagination

#2 Configure Database Credentials

After that add your database credentials in the .env file which is located in your project root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=#db_name
DB_USERNAME=#db_username
DB_PASSWORD=#db_password

#3 Generate Model and Migration

In the next step, you need to create a model and migration file in Laravel app. For generating the Model and Migration file your just need to run the following command. Here the -m generates posts migration automatically.

php artisan make:model Product -m

After that navigate database\migrations and open the database\migrations\2023_04_06_061025_create_products_table.php file and update the below code on it.

<?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('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('amount');
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

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

Now, run the migrate command to generate the table in the database.

php artisan migrate

Now open your model app\Models\Product.php and add the fallible properties same as below.

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    public $fillable = ['title', 'amount', 'description'];
}

#4 Create Routes in Laravel

Now open your routes/web.php file and put the resource routes on it. This resource route handles your all Laravel load more datausing jquery ajax.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('products', [ProductController::class, 'index'])->name('products.index');

Route::get('/', function () {
    return view('welcome');
});

#5 How to Create Controller

Now create a new controller as ProductController just running the below command.

php artisan make:controller ProductController --resource

After successfully creating the controller, now open the app/Http/Controllers/ProductController.php file and put the methods on it.

<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $products = Product::paginate(10);

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

        return view('products', compact('products'));
    }
}

#6 Create Blade View Files

In this step create a products.blade.php blade file in your resources/views directory and then open the resources\views\products.blade.php file and update the below code on it.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css">
</head>
<body>
      
<div class="container mt-5" style="max-width: 750px">
    
    <div id="product-list">
        @include('product-list')
    </div>
  
    <div class="text-center">
        <button class="btn btn-success load-more-data"><i class="fa fa-refresh"></i> Load More...</button>
    </div>
  
    <!-- Data Loader -->
    <div class="auto-load text-center" style="display: none;">
        <svg version="1.1" id="L9" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            x="0px" y="0px" height="60" viewBox="0 0 100 100" enable-background="new 0 0 0 0" xml:space="preserve">
            <path fill="#000"
                d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50">
                <animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s"
                    from="0 50 50" to="360 50 50" repeatCount="indefinite" />
            </path>
        </svg>
    </div>
</div>
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    const url = "{{ route('products.index') }}";
    let page = 1;
  
    $(".load-more-data").click(function(){
        page++;
        infinteLoadMore(page);
    });
  
    function infinteLoadMore(page) {
        $.ajax({
                url: url + "?page=" + page,
                datatype: "html",
                type: "get",
                beforeSend: function () {
                    $('.auto-load').show();
                }
            })
            .done(function (response) {
                if (response.html == '') {
                    $('.auto-load').html("We don't have more data to display :(");
                    return;
                }
                $('.auto-load').hide();
                $("#product-list").append(response.html);
            })
            .fail(function (jqXHR, ajaxOptions, thrownError) {
                console.log('Server error occured');
            });
    }
</script>
</body>
</html>

Next, create another file named as product-list.blade.php in your routes/views directory. This will be shown in the ajax render case when you create or update data this page will show the list of products.

So, open the resources\views\product-list.blade.php file and update the below code on it.

@foreach ($products as $product)
<div class="card mb-2"> 
    <div class="card-body">{{ $product->id }} 
        <h5 class="card-title">{{ $product->title }}</h5>
        <p class="card-title">{{ $product->amount }}</p>
        {!! $product->description !!}
    </div>
</div>
@endforeach

#7 Generate Dummy Data for Testing

So our laravel export CSV example functionality is almost completed, just need some dummy data in the products table. So we will add the test records using the Laravel Facker and factory.

Open the terminal create a Product Factory Class using the following command.

php artisan make:factory ProductFactory --model=Product

Now you can see in your database\factories\ProductFactory.php has a newly created file so open this file and update the same as the below code on it.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Product;

class ProductFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Product::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->title,
            'amount' => $this->faker->randomDigit,
            'description' => $this->faker->text,
        ];
    }
}

Execute the following command on the command prompt to generate or create dummy data using the tinker and factory command.

php artisan tinker
 
Product::factory()->count(20)->create()

#8 Start your app

In the last step, open the command prompt and run the following command to start the development server:

php artisan serve

Then open your browser and hit the following URL on it:

https://localhost:8000/products