Laravel 10 Auto Load More Data on Page Scroll using jQuery AJAX

Step 1: Create Route

Create a route for loading more data on page scroll.

Route::get(‘load-more-data’, ‘DataController@loadMoreData’);

Step 2: Create Controller

Create a controller DataController and add a method loadMoreData.

page;

// Fetch data from the database
$data = DB::table(‘data’)->skip(($page – 1) * 10)->take(10)->get();

// Return the data as JSON
return response()->json($data);
}
}

Step 3: Create View

Create a view file and add the following code.

@foreach($data as $item)

{{ $item->name }}

@endforeach

Step 4: Add jQuery

Add the following jQuery code to the view file.

Step 5: Add Scroll Event

Add the following jQuery code to the view file.



If you are developing social media or e-commerce websites and want to implement the “Load More” functionality to display dynamic data from a MySQL database without refreshing or reloading the page, you can utilize AJAX (Asynchronous JavaScript and XML) to achieve this. AJAX allows you to communicate with the server in the background, retrieve data, and update the web page dynamically.

By using AJAX, you can send requests to the server to fetch additional data from the MySQL database based on user interactions, such as while scrolling web page.

So, In this tutorial, you will learn how to create auto load more data on page scroll using ajax jQuery in laravel 10 applications.

Auto Load More Data on Page Scroll in Laravel 10 using jQuery AJAX

By following these steps, you can create auto load more data on page scroll using ajax jquery in Laravel 10 apps:

  • Step 1 – Installing Laravel 10 App
  • Step 2 – Connecting Database to App
  • Step 3 – Create One Model and Migration
  • Step 4 – Add Routes
  • Step 5 – Create Controller by Command
  • Step 6 – Create Blade View
  • Step 7 – Run Development Server
  • Step 8 – Test This App

Step 1 – Installing Laravel 10 App

In this step, Execute the following command on terminal to download or install the Laravel 10 app:

composer create-project --prefer-dist laravel/laravel blog

Step 2 – Connecting Database to App8

In this step, Open Laravel 10 app root directory, find .env file and setup database credential as follow:

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Step 3 – Create Model and Migration

In this step, Execute the following command on terminal to create one model and migration name Post. Use the following command and create it:

php artisan make:model Post -m

In this command -m is created the migration file

Next, go to app/database/migrations and open posts migration file and add following fields:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

After that, run the following command:

php artisan migrate

This command will create tables in your database.

Step 4 – Add Routes

In this step, open “web.php” file, which is located inside Routes directory and add the following route into web.php file:

use App\Http\Controllers\PostController;

Route::get('posts', [PostController::class, 'index']);

Step 5 – Create Controller by Command

In this step, execute the following command on terminal to create controller name PostController.php file:

php artisan make:controller PostController 

Next, go to app/http/controller/PostController and open PostController in any editor. And update the following code into your PostController file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Validator,Redirect,Response;

use App\Models\Post;

class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::paginate(8);
        $data = '';
        if ($request->ajax()) {
            foreach ($posts as $post) {
                $data.='<li>'.$post->id.' <strong>'.$post->title.'</strong> : '.$post->description.'</li>';
            }
            return $data;
        }
        return view('posts');
    }
}

Step 6 – Create a blade view

In this step, Create one blade file name posts.blade.php. And update the below HTML code into your posts.blade.php file:

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Laravel 10 load more page scroll - Tutsmake.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
   .wrapper > ul#results li {
     margin-bottom: 2px;
     background: #e2e2e2;
     padding: 20px;
     width: 97%;
     list-style: none;
   }
   .ajax-loading{
     text-align: center;
   }
</style>
</head>
 
<body>
 
  <div class="container">
   <div class="wrapper">
    <ul id="results"><!-- results appear here --></ul>
     <div class="ajax-loading"><img src="{{ asset('images/loading.gif') }}" /></div>
   </div>
  </div>
</body>
</html>

This blade view file displays your all blog posts when you scroll the page down.

Next, update the following script into your blade view file:

<script>
   var SITEURL = "{{ url('/') }}";
   var page = 1; //track user scroll as page number, right now page number is 1
   load_more(page); //initial content load
   $(window).scroll(function() { //detect page scroll
      if($(window).scrollTop() + $(window).height() >= $(document).height()) { //if user scrolled from top to bottom of the page
      page++; //page number increment
      load_more(page); //load content   
      }
    });     
    function load_more(page){
        $.ajax({
           url: SITEURL + "posts?page=" + page,
           type: "get",
           datatype: "html",
           beforeSend: function()
           {
              $('.ajax-loading').show();
            }
        })
        .done(function(data)
        {
            if(data.length == 0){
            console.log(data.length);
            //notify user if nothing to load
            $('.ajax-loading').html("No more records!");
            return;
          }
          $('.ajax-loading').hide(); //hide loading animation once data is received
          $("#results").append(data); //append data into #results element          
           console.log('data.length');
       })
       .fail(function(jqXHR, ajaxOptions, thrownError)
       {
          alert('No response from server');
       });
    }
</script>

Step 7 – Run Development Server

In this step, execute the php artisan serve command on termianl to start development server locally:

php artisan serve

Step 8 – Test This App

Open browser and hit the following url on it:

http://127.0.0.1:8000/posts

Conclusion

Laravel 10 ajax infinity load more on page scroll example tutorial, you have learned how to implement ajax load more data on page scroll in Laravel 10 apps.

Recommended Laravel Posts

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?