Last active
July 26, 2021 05:52
-
-
Save patrickcurl/220f7ee0c52bfc8fbc368acaf5e265ff to your computer and use it in GitHub Desktop.
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\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