Laravel Load More Data on Scroll with jQuery and Ajax

Today we are going to learn Laravel Load More Data on Scroll with jQuery and Ajax. You may notice while using Facebook and Twitter the timeline data or posts loads more data when reach at the end of page.

This way, server doesn’t need to load all data in single view and provide smooth user experience.

We are going to create a Laravel Application with the same method also we will show a method on how to add button and show more data. So follow the step.

Also Read : Create Custom Helper in CodeIgniter (2022)

Step for Laravel Load More Data on Scroll with jQuery and Ajax

  • Step 1: Creating fresh New Laravel Application
  • Step 2: Creating Database and Configuration
  • Step 3: Creating Migration
  • Step 4: Creating Post Model
  • Step 5: Creating Controllers
  • Step 6: Creating Routes
  • Step 7: Creating a Blade View
  • Step 8: Adding Fake Posts Data for Testing
  • Step 9: Conclusion

Creating fresh New Laravel Application

First, We are going to install a fresh new Laravel application. Open the terminal and run the following command to create a new Laravel Application:

composer create-project laravel/laravel load-more
cd load-more

“load-more” is our Laravel application name.

Creating Database and Configuration

Now we are going to create a database. First open phpmyadmin and create a new database with a name load-more.

Creating Database - Laravel Load More Data on Scroll with jQuery and Ajax
Creating Database

Now, We need to configure Laravel database. To configure Laravel database open .env file which can be found on root of the application.

Also Read : Integration PayPal Payment Gateway in PHP

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=load-more
DB_USERNAME=root
DB_PASSWORD=
Laravel Database Configuration - Laravel Load More Data on Scroll with jQuery and Ajax
Laravel Database Configuration 8211 Laravel Load More Data on Scroll with jQuery and Ajax

Creating Migration

Now we will create a posts migration. To create a posts migration run the following command in the terminal:

php artisan make:migration create_posts_table  

This command will create a migration file under database/migrations directory as you can seen in the image.

Creating Posts Migration File
Creating Posts Migration File

Open the file and add two fields for posts migration.

<?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->text('body');
            $table->timestamps();
        });
    }

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

Now, After adding the two fields run the migration.

php artisan migrate

Creating Post Model

Now, Its time to create a post model. To create a post model run the following command in terminal.

php artisan make:model Post

This will create Post model class at app/Models directory as you can seen in image.

Creating Post Model
Creating Post Model

Also Read : Drag & Drop Reorder Images in PHP (2022)

Creating Controllers

Now in this step, we will create a controller class which defines method to load view and fetch data. To create a controller run the following command.

php artisan make:controller PostController

This will create a class app/Http/Controllers/PostController.php file.

Creating Post Controller
Creating Post Controller

Open file and add new method in it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    //View Post Page
    public function post(Request $request)
    {
        $posts = Post::paginate(8);

        if ($request->ajax()) {
            $html = '';

            foreach ($posts as $post) {
                $html.='<div class="mt-5"><h1>'.$post->title.'</h1><p>'.$post->body.'</p></div>';
            }

            return $html;
        }

        return view('post');
    }
}

Creating Routes

Now we are going to create route to handle view in 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!
|
*/

//This is a default route
Route::get('/', function () {
    return view('welcome');
});


Route::get('post', [PostController::class, 'post'])->name('post');

Also Read : Create a custom WordPress Plugin from scratch (2022)

Creating a Blade View

Now we are going to create a blade file post.blade.php file in resources/views directory. Add the below HTML view in it.

Loading data when scroll:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Posts - LaravelTuts</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        main > .container {
            padding: 60px 15px 0;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">LaravelTuts</a>
            </div>
        </nav>
    </header>
    <main class="flex-shrink-0">
        <div class="container" id="post">
            {{-- here loads posts --}}
        </div>
        <p class="text-center loading">Loading...</p>
    </main>
    <script type="text/javascript">
        var paginate = 1;
        loadMoreData(paginate);
        $(window).scroll(function() {
            if($(window).scrollTop() + $(window).height() >= $(document).height()) {
                paginate++;
                loadMoreData(paginate);
              }
        });
        // run function when user reaches to end of the page
        function loadMoreData(paginate) {
            $.ajax({
                url: '?page=' + paginate,
                type: 'get',
                datatype: 'html',
                beforeSend: function() {
                    $('.loading').show();
                }
            })
            .done(function(data) {
                if(data.length == 0) {
                    $('.loading').html('No more posts.');
                    return;
                  } else {
                    $('.loading').hide();
                    $('#post').append(data);
                  }
            })
               .fail(function(jqXHR, ajaxOptions, thrownError) {
                  alert('Something went wrong.');
               });
        }
    </script>
</body>
</html>

Loading data when button press:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Posts - LaravelTuts</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        main > .container {
            padding: 60px 15px 0;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">LaravelTuts</a>
            </div>
        </nav>
    </header>
    <main class="flex-shrink-0">
        <div class="container" id="post">
            {{-- here loads posts --}}
        </div>
        <div class="text-center m-3">
            <button class="btn btn-primary" id="load-more" data-paginate="2">Load more...</button>
            <p class="invisible">No more posts...</p>
        </div>
    </main>
    <script type="text/javascript">
        var paginate = 1;
        loadMoreData(paginate);

        $('#load-more').click(function() {
            var page = $(this).data('paginate');
            loadMoreData(page);
            $(this).data('paginate', page+1);
        });
        // run function when user click load more button
        function loadMoreData(paginate) {
            $.ajax({
                url: '?page=' + paginate,
                type: 'get',
                datatype: 'html',
                beforeSend: function() {
                    $('#load-more').text('Loading...');
                }
            })
            .done(function(data) {
                if(data.length == 0) {
                    $('.invisible').removeClass('invisible');
                    $('#load-more').hide();
                    return;
                  } else {
                    $('#load-more').text('Load more...');
                    $('#post').append(data);
                  }
            })
               .fail(function(jqXHR, ajaxOptions, thrownError) {
                  alert('Something went wrong.');
               });
        }
    </script>
</body>
</html>

Adding Fake Posts Data for Testing

You will also need to create fake data. You can use Laravel factory to create dummy data. Or run the below SQL query multiple tiles in MySQL command line.

INSERT INTO `posts` (`id`, `title`, `body`, `created_at`, `updated_at`) VALUES (NULL, 'This is post heading', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.', NULL, NULL);

Now, Everything is completed you can run the server and test the application by the following command:

php artisan serve

Now, Open the following URL in browser:

http://127.0.0.1:8000/post

Conclusion

We had learn Laravel Load More Data on Scroll with jQuery and Ajax. Hope this tutorial helped you with learning Laravel. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read : Create CRUD Application with Laravel and Vue.js

4 Comments

Leave a Reply