Created
November 20, 2023 15:53
-
-
Save MrPunyapal/d4a238d806ec99d868efd98d67a627f1 to your computer and use it in GitHub Desktop.
Optimized Load More Laravel livewire
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> | |
@if ($loadMore) | |
<table> | |
@if ($offset == 0) | |
<thead> | |
<tr> | |
<th>#</th> | |
<th>Title</th> | |
<th>description</th> | |
</tr> | |
</thead> | |
@endif | |
<tbody> | |
@foreach ($posts as $post) | |
<tr> | |
<td>{{ $loop->iteration + $offset }}</td> | |
<td>{{ $post->title }}</td> | |
<td>{{ $post->description }}</td> | |
</tr> | |
@endforeach | |
</tbody> | |
</table> | |
@livewire('post-list', ['loadMore' => false, 'offset' => $offset + $limit], key($offset)) | |
@else | |
<button wire:click="$set('loadMore',true)">Load More</button> | |
@endif | |
</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\Livewire; | |
use App\Models\Post; | |
use Livewire\Component; | |
class PostList extends Component | |
{ | |
public $offset = 0; | |
public $limit = 10; | |
public $posts; | |
public $loadMore; | |
public function mount($loadMore = true, $offset = 0) | |
{ | |
$this->loadMore = $loadMore; | |
$this->offset = $offset; | |
} | |
public function render() | |
{ | |
if ($this->loadMore) { | |
$this->posts = Post::offset($this->offset)->limit($this->limit)->get(); | |
} | |
return view('livewire.post-list'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment