Load More Data on Page Scroll using AJAX Example In Laravel 10

  Nov 2023
  ITSolutionsGuides
  Category: Laravel
Load More Data on Page Scroll using AJAX Example In Laravel 10

Hi Developers,

In this tutorial, we'll explore how to implement an intuitive "Load More on Scroll" feature in Laravel 10 using AJAX. Enabling automatic data loading as users scroll down the page can significantly enhance the overall user experience of your web application. Leveraging the power of Laravel 10 and AJAX, we'll create a seamless and dynamic content loading mechanism.

To achieve this, we'll employ AJAX requests triggered by the scroll event, ensuring that additional data is fetched and seamlessly appended to the existing content. This tutorial will guide you through the process of setting up the necessary routes, controllers, and views in Laravel 10, as well as incorporating jQuery for smooth AJAX functionality.

By the end of this tutorial, you'll have a fully functional auto-load feature that dynamically fetches and displays more data as users scroll down the page. This implementation not only optimizes page loading times but also provides a modern and engaging user interface. Elevate your Laravel 10 application with this simple yet impactful enhancement in user interaction.

Learn to implement infinite scrolling in Laravel 10 using AJAX. Dynamically load more data as users scroll, enhancing user experience.

Lets Create the Migration

Lets install the new Laravel Application and lets create the new posts migration table and the Modal for the migration using the following artisan command

php artisan make:model Post -m

the above artisan command will create both the migration and the modal, In the migration file

<?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('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Lets Edit The Modal

Lets make changes in the Modal file

app/Models/Post.php

<?php
    
namespace App\Models;
    
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
    
class Post extends Model
{
    use HasFactory;
   
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'body', 'slug'
    ];
}

Lets Create Factory Class

To generate more dummy records lets use the factory class for creating the records to load the data dynamically on page scroll, The Factory class is created by using the following Artisan command,

php artisan make:factory PostFactory --model=Post

after running the above command the factory class file for the Post Modal will be created

database\factories\PostFactory.php

<?php
    
namespace Database\Factories;
    
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Post;
use Illuminate\Support\Str;
    
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;
      
    /**
     * Define the model's default state.
     *
     * @return array

     */
    public function definition(): array
    {
        return [
            'title' => $this->faker->text(),
            'slug' => Str::slug($this->faker->text()),
            'body' => $this->faker->paragraph()
        ];
    }
}

Lets Create the Routes

lets run the factory class by using the following Artisan command
php artisan tinker

folloowed by the command
Post::factory()->count(20)->create()

this will generate 20 dummy records. Then in the web route file,

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PostController;
   
/*
|--------------------------------------------------------------------------
| 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('posts',[PostController::class,'index'])->name('posts.index');

Lets Create the Controller

Lets create the controller using the following artisan command

php artisan make:controller PostController

the above artisan command will create the PostController controller file,
app/Http/Controllers/PostController.php

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

Lets Create the Blade Files

We are using two blade files , one for the layout and another one for loading the data ,

Both the blade files are linked through the @include blade directive,

resources/views/posts.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Load More Data on Page Scroll using AJAX Example In Laravel 10</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: 750px">
  
    <h1>Load More Data on Page Scroll using AJAX Example In Laravel 10</h1>
  
    <div id="data-wrapper">
        @include('data')
    </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>
    var ENDPOINT = "{{ route('posts.index') }}";
    var page = 1;
  
    /*------------------------------------------
    --------------------------------------------
    Call on Scroll
    --------------------------------------------
    --------------------------------------------*/
    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() >= ($(document).height() - 20)) {
            page++;
            infinteLoadMore(page);
        }
    });
  
    /*------------------------------------------
    --------------------------------------------
    call infinteLoadMore()
    --------------------------------------------
    --------------------------------------------*/
    function infinteLoadMore(page) {
        $.ajax({
                url: ENDPOINT + "?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();
                $("#data-wrapper").append(response.html);
            })
            .fail(function (jqXHR, ajaxOptions, thrownError) {
                console.log('Server error occured');
            });
    }
</script>
</body>
</html>

Lets Create the Blade File

resources/views/data.blade.php

@foreach ($posts as $post)
<div class="card mb-2"> 
    <div class="card-body">{{ $post->id }} 
        <h5 class="card-title">{{ $post->title }}</h5>
        {!! $post->body !!}
    </div>
</div>
@endforeach

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides