Laravel 8 Load More Data on Page Scroll using Ajax Jquery

Laravel 8 auto load more data on page scroll using jQuery ajax example. In this post, i will show you how to create load more data on infinity page scroll in laravel 8 using jQuery and ajax.

Note that, we will not use button click for load more data in laravel 8.

In this post example, i will write simple jQuery ajax code for load more data on infinity page scroll in laravel 8 using jQuery and ajax app.

And, you will learn step by step how to implement laravel 8 infinite page scroll and load more data on page using jQuery ajax.

Ajax Auto Load More Data on Page Scroll Laravel

  • Step 1 – Install Laravel 8 Application
  • Step 2 – Database Configuration
  • Step 3 – Make Model and Migration
  • Step 4 – Make Routes
  • Step 5 – Creating Controller
  • Step 6 – Create Load More Blade View
  • Step 7 – Start Development Server
  • Step 8 – Run This App On Browser

Step 1 – Install Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

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

Step 2 – Database Configuration

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Make Model and Migration

In step 3, create one model and migration name Post using the following command:

php artisan make:model Post -m

After that, open create_posts_table.php file, which is located inside /database/migrations/ directory. And add the following code in it:

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

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

Then, open Post.php file which is located inside app/Models directory. And add the following code into it:

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'description'
    ];
}

Then run the following command on command prompt to create posts table into database:

php artisan migrate

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Controllers\PostController;

Route::get('load-more', [PostController::class, 'index']);

Step 5 – Creating Controller

In step 5, create controller by using the following command:

php artisan make:controller PostController

The above command will create PostController.php file, which is located inside LaravelLoadMore/app/Http/Controllers/ directory.

Add the following code in PostController.php file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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('load-more-data');
    }

}

Step 6 – Create Load More Blade View

In step 6, create new blade view file that named load-more-data.blade.php inside resources/views directory for load more data from database on page scroll.

And add the following jQuery and ajax code will load more data on page scroll using ajax jQuery Laravel 8 Appl:

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

Don’t worry i have already added the jQuery ajax code and library to auto load more data on page scroll laravel on blade views.

So, you can add the following php and html form code into load-more-data.blade.php:

<!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 8 Auto Load More on Page Scroll - LaraTutorials.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>
<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>
</html>

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server:

php artisan serve

Step 8 – Run This App On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/load-more

Recommended Laravel Tutorials

Leave a Comment