Create Laravel 8 Auto Load More Data on Page Scroll with AJAX

Last updated on by Digamber

How to auto load more data on page scroll in Laravel 8 app? throughout this detailed guide, you wil find out the quickest and easiest way to learn about how to dynamically autoload the data on infinite page scroll in laravel application with the help of jQuery AJAX (Asynchronous JavaScript And XML).

The topmost applications use the infinite page scroll technique to load more data. For instance, Facebook, Twitter, Tumblr, Instagram, and many more profound apps use this auto load more data on infinite page scroll to make the interaction more interactive and user-friendly. When you reach their feed section, you scroll to infinite, and the data gets loaded automatically.

So, in this laravel infinite scroll tutorial, we are going to replace the laravel pagination pattern with load more data on page scroll in laravel using jQuery AJAX.

Laravel 8 Auto Load More Data On Page Scroll Example

You need to gradually complete the following steps for creating the feature of auto loading the data from the server or database while scrolling in laravel using jQuery AJAX.

  • Step: 1 – Create Laravel Project
  • Step: 2 – Make Database Connection
  • Step: 3 – Create Mode and Run Migration
  • Step: 4 – Generate Dummy Data with Tinker Factory
  • Step: 5 – Generate and Set Up Controller
  • Step: 6 – Create Routes
  • Step: 7 – Set Up View
  • Step: 8 – Start server and Run Project

Create Laravel Project

Ensure you have the composer tool installed on your system, further open the terminal, and execute the command to create the laravel project.

composer create-project laravel/laravel laravel-auto-load-more --prefer-dist

Make Database Connection

Secondly, insert the database name, username and password in .env file:

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

Create Mode and Run Migration

Subsequently, you have to create a Model, plus it will help manifest the table into the database.

Ergo, invoke the command to generate the Blog model:

php artisan make:model Blog -m

Next, update the below code in database/migrations/create_blogs_table.php file:

<?php

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

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

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

Add following code in app/Models/Blog.php file:

<?php

namespace App\Models;

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

class Blog extends Model
{
    use HasFactory;
    protected $fillable = [
        'post_name',
        'post_description'
    ];
}

After that, open a terminal window and execute the artisan migration command:

php artisan migrate

Add Test Data

This step explains how to generate dummy data using factory; this data loads dynamically on page scroll:

php artisan make:factory BlogFactory --model=Blog

Further, put the below code in database\factories\BlogFactory.php:

<?php

namespace Database\Factories;

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

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

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

Open terminal, execute the below commands to generate the test data:

php artisan tinker
Blog::factory()->count(200)->create()

Generate and Set Up Controller

Now, you need a controller in which we will add the functions to invoke blade view and fetch blog data from the database. Thus, run command to generate a blog controller file:

php artisan make:controller BlogController

Further, add the following code in the app/Http/Controllers/BlogController.php file:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Blog; 
use Validator;
use Redirect;
use Response;

class BlogController extends Controller
{
    public function getArticles(Request $request)
    {
        $results = Blog::orderBy('id')->paginate(10);
        $artilces = '';
        if ($request->ajax()) {
            foreach ($results as $result) {
                $artilces.='<div class="card mb-2"> <div class="card-body">'.$result->id.' <h5 class="card-title">'.$result->post_name.'</h5> '.$result->post_description.'</div></div>';
            }
            return $artilces;
        }
        return view('welcome');
    }    
}

Create Route

In the subsequent step, create route with the to make the GET request to fetch the data for adding into infinite scroll component. Thus, add the below code in the routes/web.php file:

<?php

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


Route::get('/blogs', [BlogController::class, 'getArticles']);

Set up Blade View Template

Besides, to invoke the view, you need to create a blade view file. Notwithstanding, we are using the existing welcome blade view template.

Thereupon, insert the following code in the resources/views/welcome.blade.php file:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Laravel dynamic auto load more page scroll examle</title>

    <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: 550px">
        <div id="data-wrapper">
            <!-- Results -->
        </div>

        <!-- Data Loader -->
        <div class="auto-load text-center">
            <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>
        var ENDPOINT = "{{ url('/') }}";
        var page = 1;
        infinteLoadMore(page);

        $(window).scroll(function () {
            if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
                page++;
                infinteLoadMore(page);
            }
        });

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

    </script>
</body>

</html>

Start server and Run Project

Now that everything has been done, wherefore start the laravel application with the following command:

php artisan serve

Open the browser plus add the following url on the address bar to test the project:

http://127.0.0.1:8000/blogs

Laravel Load More Example

Conclusion

Finally, this tutorial is completed. Through this step-by-step guide, you learned about Laravel 8 AJAX dynamic load more data on infinite page scroll. I reckon from now on, you can quickly and easily implement AJAX load more data on page scroll in laravel application.