Skip to content

Instantly share code, notes, and snippets.

@patrickcurl
Last active July 26, 2021 05:52
Show Gist options
  • Save patrickcurl/220f7ee0c52bfc8fbc368acaf5e265ff to your computer and use it in GitHub Desktop.
Save patrickcurl/220f7ee0c52bfc8fbc368acaf5e265ff to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Illuminate\Pagination\Cursor;
use Illuminate\Support\Collection;
use Livewire\Component;
class InfinitePosts extends Component
{
public $posts; // holds are list of posts.
public $nextCursor; // holds our current page position.
public $hasMorePages; // Tells us if we have more pages to paginate.
/**
* Initialize data
* @return void
*/
public function mount()
{
$this->posts = new Collection(); // initialize the data
$this->loadPosts(); // load the data
}
/**
* Load data and maintain cursor state
*
*/
public function loadPosts()
{
if ($this->hasMorePages !== null && !$this->hasMorePages) {
return;
}
$posts = Post::cursorPaginate(
15,
['*'],
'cursor',
Cursor::fromEncoded($this->nextCursor)
);
$this->posts->push(...$posts->items());
$this->hasMorePages = $posts->hasMorePages();
if ($this->hasMorePages === true) {
$this->nextCursor = $posts->nextCursor()->encode();
}
}
/**
* Render our component
*
*/
public function render()
{
return view('livewire.infinite-posts')->layout('layouts.guest');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment