Laravel 8 - Auto Load More Data on Page Scroll with AJAX with Example

  392 views   2 weeks ago Laravel jQuery

Hello Dev.

This detailed article, will provide 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.

The topmost programs use the infinite web page scroll technique to load more records. for example, fb, Twitter, Tumblr, Instagram, and plenty of greater profound apps use this auto load extra information on limitless page scroll to make the interaction greater interactive and user-friendly. while you reach their feed phase, you scroll to countless, and the data gats loaded routinely.

So, on this laravel infinite scroll academic, we are going to replace the laravel pagination sample with load more data on page scroll in laravel the usage of jQuery AJAX.

Laravel 8 Auto Load More Data On Page Scroll For Instance.

You need to step by step complete the following steps for developing the feature of auto loading the data from the server or database while scrolling in laravel the use of jQuery AJAX.
1. Create Laravel Project
2. Configuration of Database
3. Set Up Migration and Model
4. Generate Dummy Data Using Tinker
5. Generate and Configure Controller
6. Create and Add Routes
7. Create Blade View
8. Run Development Server

Step 1: Create Laravel Project

first of all we want to get clean and new Laravel eight version application the use of bellow command, now open your terminal OR command prompt and then fire bellow command and run it(However, you may ignore this step if the app is already created):

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

Step 2: Configuration of Database

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

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

Step 3: Set Up Migration and Model

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
create_blogs_table.php

<?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
Blog.php

<?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

Step 4: Generate Dummy Data Using Tinker

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

php artisan make:factory BlogFactory --model=Blog

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

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()

Step 5: Generate and Configure 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

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

BlogController.php

<?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');
    }    
}

Step 6: Create and Add Routes

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

web.php

<?php

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

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

Step 7: Create Blade View

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

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

welcome.blade.php

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

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

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

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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>

Step 8: Run Development Server

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
Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]

Related Articles