Share this:

In the modern era of web development, seamless user experience is paramount. Infinite scrolling, a technique where more content is loaded automatically as users scroll down a page, has become increasingly popular.

This method keeps users engaged and eliminates the need for pagination. In this tutorial, we will walk you through implementing AJAX-based infinite scrolling in a Laravel 10 application.

By the end of this guide, you will have a solid understanding of the components and process involved in creating this feature.

Table of Contents:

  1. Prerequisites
  2. Setting up a New Laravel 10 Project
  3. Creating the Database and Model
  4. Generating Seed Data
  5. Building the Controller
  6. Creating the Blade View
  7. Implementing AJAX-based Infinite Scrolling
  8. Testing and Final Thoughts

Prerequisites:

Before diving into the tutorial, make sure you have the following tools and software installed on your system:

  • PHP (7.3 or higher)
  • Composer (Latest version)
  • Laravel Installer (Latest version)
  • MySQL or any other database system
  • Text editor or IDE (e.g., Visual Studio Code, PhpStorm)

Setting up a New Laravel 10 Project:

To begin, create a new Laravel project using the Laravel installer or Composer. Open your terminal and run one of the following commands:

Using Laravel installer:

laravel new laravel-infinite-scroll

Using Composer:

composer create-project --prefer-dist laravel/laravel laravel-infinite-scroll

After the installation is complete, navigate to the project directory:

cd laravel-infinite-scroll

Next, open the project in your preferred text editor or IDE. Locate the .env file in the project root and configure the database credentials.

Creating the Database and Model:

To store our sample data, we need to create a database table and a corresponding Laravel Eloquent model. In this example, we will create a “posts” table with three columns: id, title, and content. Run the following command to create a migration file:

php artisan make:migration create_posts_table --create=posts

Open the newly created migration file in the database/migrations directory and update the up method as follows:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

Now, run the migration to create the “posts” table:

php artisan migrate

Next, generate a model for the “posts” table using the following command:

php artisan make:model Post

Generating Seed Data:

To test our infinite scrolling feature, we need sample data in the “posts” table. Laravel provides a convenient way to generate dummy data using seeders and factories. First, create a factory for the Post model:

php artisan make:factory PostFactory --model=Post

Open the newly created factory in the database/factories directory and define the factory definition:

public function definition()
{
    return [
        'title' => $this->faker->sentence,
        'content' => $this->faker->paragraphs(3, true),
    ];
}

Next, create a seeder to insert sample data into the “posts” table:

php artisan make:seeder PostsTableSeeder

Update the run method in the PostsTableSeeder class to use the Post factory:

public function run()
{
    Post::factory(100)->create();
}

Finally, update the DatabaseSeeder class to call the PostsTableSeeder:

public function run()
{
    $this->call(PostsTableSeeder::class);
}

Now, seed the database with the sample data:

php artisan db:seed

Building the Controller:

To fetch and serve the posts data, we need to create a controller. Generate a new controller using the following command:.

php artisan make:controller PostController

In the PostController class, add a method called index that retrieves and returns the posts:

use Illuminate\Support\Facades\Response;
use App\Models\Post;

public function index(Request $request)
{
    $posts = Post::latest()->paginate(10);

    if ($request->ajax()) {
        $view = view('posts.load', compact('posts'))->render();
        return Response::json(['view' => $view, 'nextPageUrl' => $posts->nextPageUrl()]);
    }

    return view('posts.index', compact('posts'));
}

This method fetches the latest posts and paginates them, 10 posts per page. If the request is an AJAX request, it returns the rendered HTML of the posts. Otherwise, it returns the main view.

Creating the Blade View:

Now, we need to create two Blade views: index.blade.php and load.blade.php. The index view will serve as the main template, while the load view will be used to render new posts when the user scrolls down.

Create a new directory named posts in the resources/views directory, then create the two views inside it. First, let’s set up the index.blade.php view:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 10: Implementing AJAX-Based Infinite Scrolling for Seamless Data Loading - LaravelTuts.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <h2 class="mb-4">Posts</h2>
        <div id="posts-container">
            @include('posts.load')
        </div>
    </div>

    <script>
        // Implement AJAX-based infinite scrolling here.
    </script>
</body>
</html>

Next, create the load.blade.php view that will display the posts:

@foreach($posts as $post)
    <div class="card mb-4">
        <div class="card-header">
            {{ $post->title }}
        </div>
        <div class="card-body">
            <p>{{ $post->content }}</p>
        </div>
    </div>
@endforeach

<div class="d-none">
    {{ $posts->links() }}
</div>

Implementing AJAX-based Infinite Scrolling:

Now, we will add the JavaScript code for the infinite scrolling feature to the index.blade.php view:

$(document).ready(function () {
    let nextPageUrl = '{{ $posts->nextPageUrl() }}';

    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
            if (nextPageUrl) {
                loadMorePosts();
            }
        }
    });

    function loadMorePosts() {
        $.ajax({
            url: nextPageUrl,
            type: 'get',
            beforeSend: function () {
                nextPageUrl = '';
            },
            success: function (data) {
                nextPageUrl = data.nextPageUrl;
                $('#posts-container').append(data.view);
            },
            error: function (xhr, status, error) {
                console.error("Error loading more posts:", error);
            }
        });
    }
});

This script checks if the user has scrolled close to the bottom of the page. If so, it sends an AJAX request to load the next set of posts. The `nextPageUrl` variable stores the URL for the next page of posts.

Once the request is successful, the script appends the new posts to the `posts-container` div and updates the `nextPageUrl` for future requests.

Testing and Final Thoughts:

Finally, let’s test our infinite scrolling feature. Register the route for the `index` method in the `routes/web.php` file:

use App\Http\Controllers\PostController;

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

Start the Laravel development server:

php artisan serve

Visit http://127.0.0.1:8000/posts in your browser and start scrolling down. You should see new posts being loaded automatically as you reach the bottom of the page.

Preview:

Implementing AJAX-Based Infinite Scrolling for Seamless Data Loading Laravel 10
Implementing AJAX-Based Infinite Scrolling for Seamless Data Loading Laravel 10
Implementing AJAX-Based Infinite Scrolling for Seamless Data Loading Laravel 10
Implementing AJAX-Based Infinite Scrolling for Seamless Data Loading Laravel 10

Congratulations! You have successfully implemented AJAX-based infinite scrolling in a Laravel 10 application. This feature enhances user experience by providing seamless data loading. You can now adapt this technique to various use cases, such as loading comments, products, or any other content that benefits from infinite scrolling.

Conclusion

In conclusion, AJAX-based infinite scrolling is a useful feature that enhances user experience by providing seamless data loading. By following this tutorial, you should now have a better understanding of how to implement this feature in your Laravel 10 application. You can customize this technique to suit your specific needs, such as loading comments, products, or any other content that benefits from infinite scrolling.

Source Code

Share this:

Categorized in: