Created
May 11, 2022 12:52
-
-
Save NigelDorning/5bf271c3329ebb1345e3ceb3e2173acb to your computer and use it in GitHub Desktop.
Infinite pagination with 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
<!-- The Livewire Component --> | |
<?php | |
namespace App\Http\Livewire; | |
use Livewire\Component; | |
use Illuminate\Support\Facades\Http; | |
class Posts extends Component | |
{ | |
public $page = 1; | |
public $totalPages; | |
public $posts = []; | |
public function mount() | |
{ | |
$this->getPosts(); | |
} | |
public function loadMore() | |
{ | |
if ($this->page < $this->totalPages) { | |
$this->page++; | |
$this->getPosts(); | |
} | |
} | |
public function getPosts() | |
{ | |
$response = Http::get(url('ajax-posts'), [ | |
'page' => $this->page | |
])->json(); | |
array_push($this->posts, ...$response['data']); | |
$this->totalPages = $response['last_page']; | |
} | |
public function render() | |
{ | |
return view('livewire.posts'); | |
} | |
} | |
?> | |
<!-- The Livewire View --> | |
<div> | |
<ul> | |
@foreach($posts as $post) | |
<li>{{ $post['id'] }} - {{ $post['title'] }}</li> | |
@endforeach | |
</ul> | |
<button wire:click="loadMore">Load More</button> | |
</div> | |
<!-- The Single Action Controller --> | |
<?php | |
namespace App\Http\Controllers; | |
use App\Models\Post; | |
use Illuminate\Http\Request; | |
class PostsController extends Controller | |
{ | |
/** | |
* Handle the incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return \Illuminate\Http\Response | |
*/ | |
public function __invoke(Request $request) | |
{ | |
return Post::paginate(20, ['*'], 'page'); | |
} | |
} | |
?> | |
<!-- The Routes --> | |
<?php | |
use App\Http\Livewire\Posts; | |
use Illuminate\Support\Facades\Route; | |
use App\Http\Controllers\PostsController; | |
/* | |
|-------------------------------------------------------------------------- | |
| Web Routes | |
|-------------------------------------------------------------------------- | |
| | |
| Here is where you can register web routes for your application. These | |
| routes are loaded by the RouteServiceProvider within a group which | |
| contains the "web" middleware group. Now create something great! | |
| | |
*/ | |
Route::get('/', App\Http\Livewire\HomePage::class); | |
Route::get('/ajax-posts', PostsController::class); | |
Route::get('/posts', Posts::class); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment