Skip to content

Instantly share code, notes, and snippets.

@davidgrzyb
Last active November 6, 2023 18:29
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save davidgrzyb/dee800007f764683b8cb830257c22116 to your computer and use it in GitHub Desktop.
Save davidgrzyb/dee800007f764683b8cb830257c22116 to your computer and use it in GitHub Desktop.
Livewire Infinite Scroll Example
<div class="container mx-auto p-10">
<h1 class="text-4xl font-semibold text-center mt-4 mb-6">Users</h1>
<table wire:loading.delay.class="opacity-50" class="table-auto w-full">
<thead>
<tr>
<th class="px-4 py-2">Name</th>
<th class="px-4 py-2">Email</th>
<th class="px-4 py-2">Created At</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr @if ($loop->last) id="last_record" @endif>
<td class="border px-4 py-2">{{ $user->name }}</td>
<td class="border px-4 py-2">{{ $user->email }}</td>
<td class="border px-4 py-2">{{ $user->created_at->diffForHumans() }}</td>
</tr>
@endforeach
</tbody>
</table>
@if ($loadAmount >= $totalRecords)
<p class="text-gray-800 font-bold text-2xl text-center my-10">No Remaining Records!</p>
@endif
<script>
const lastRecord = document.getElementById('last_record');
const options = {
root: null,
threshold: 1,
rootMargin: '0px'
}
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
@this.loadMore()
}
});
});
observer.observe(lastRecord);
</script>
</div>
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
class UsersTable extends Component
{
public $totalRecords;
public $loadAmount = 10;
public function loadMore()
{
$this->loadAmount += 10;
}
public function mount()
{
$this->totalRecords = User::count();
}
public function render()
{
return view('livewire.users-table')
->with(
'users',
User::orderBy('created_at', 'desc')
->limit($this->loadAmount)
->get()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment