• Reading time ~ 4 min
  • 22.08.2023

Throughout this tutorial, you will determine how to load more data on page scroll in the laravel application using the laravel livewire package.

Load more or infinite scrolling is an immaculate way to show products, posts, or data on websites. Research says that scroll data loading is the best way to enhance user engagement; however, pagination is the traditional way to display data on websites.

This Laravel Livewire Load More OnScroll tutorial will help you implement the load more data on the scroll from scratch.

Livewire is a full-stack framework exclusively built for Laravel that reduces the pain of creating dynamic user interfaces without compromising on quality and keeps the warmth of Laravel.

Here are the steps towards building and implementing load more data on infinity scroll in the laravel application using the livewire package.

  • Create Laravel Project
  • Make Database Connection
  • Invoke Migration in Laravel
  • Generate Test Data
  • Install Livewire Package
  • Build Laravel Load More Component
  • Add Route in Laravel
  • Setting Up View
  • Test Application

Create Laravel Project

Make sure you have configured the composer on your development system. Head over to the console, open the terminal, enter the below command, and evoke the installation process:

composer create-project laravel/laravel laravel-load-more-example --prefer-dist

Make Database Connection

Open the .env file and add your database credentials such as database name, username equally important password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Invoke Migration in Laravel

Next, you have to run the migration using existing laravel migration files. But make sure you started the development server if developing locally.

So head over to the console and execute the below command:

php artisan migrate

Generate Test Data

Now, to test the load more feature, you need to have test data in your database, so open the console and execute the following commands:

php artisan tinker

With the above command you entered inside the Psy Shell, further append the Model name and pass the number of the test records you are willing to generate:

User::factory()->count(200)->create()

Install Livewire Package

Use the composer command to install livewire library in laravel app:

composer require livewire/livewire

Build Laravel Load More Component

Now, you need to generate the livewire load more components with the following command.

php artisan make:livewire load-more-user-data

Ultimately, the above command manifested two files on the following path:

app/Http/Livewire/LoadMoreUserData.php
resources/views/livewire/load-more-user-data.blade.php

Open and update the below code in app/Http/Livewire/LoadMoreUserData.php file:

<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\User;
class LoadMoreUserData extends Component
{
    public $limitPerPage = 10;
    protected $listeners = [
        'load-more' => 'loadMore'
    ];
   
    public function loadMore()
    {
        $this->limitPerPage = $this->limitPerPage + 6;
    }
    public function render()
    {
        $users = User::latest()->paginate($this->limitPerPage);
        $this->emit('userStore');
        return view('livewire.load-more-user-data', ['users' => $users]);
    }
}

Open and update the below code in resources/views/livewire/load-more-user-data.blade.php file:

<div>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>#Id</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>

Add Route in Laravel

Next, add a route in the routes/web.php file; this will be a simple GET method to load users’ data on the scroll.

<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/
Route::get('/load-more-users', function () {
    return view('welcome');
});

Setting Up View

In this final step you have to open the resources/views/welcome.blade.php file and add the following code:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel Livewire Load More Data on Page Scroll Demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        html,
        body {
            height: 100vh;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        @livewire('load-more-user-data')
    </div>
    @livewireScripts
    <script type="text/javascript">
        window.onscroll = function (ev) {
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
                window.livewire.emit('load-more');
            }
        };
    </script>
</body>
</html>

Test Application

Finally, you need to start the laravel application, so open the terminal window and execute the below command.

php artisan serve

Here is the URL on which you can test the app:

http://localhost:8000/load-more-users

Conclusion

The Laravel Livewire Load More OnScroll tutorial is over; in this tutorial, we learned the easiest way to integrate on scroll loads more in the laravel application using the livewire library.

I reckon you liked this tutorial and share it with others.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297