Last active
November 6, 2023 18:29
-
-
Save davidgrzyb/dee800007f764683b8cb830257c22116 to your computer and use it in GitHub Desktop.
Livewire Infinite Scroll Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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