Laravel InertiaJS Pagination
I was looking for the proper way to do pagination on Inertia JS official documentation website. Unfortunately, there is still no such related content available yet.
However, when wandering around InertiaJS Github profile, I noticed a somewhat official (as the code was found inside a repo of InertiaJS) solution.
0x0 — Result
After applying the solution, I was able to pass the paginated data members
to frontend. The data
field is an array of your paginated model and the links
field is an array of the links you are able to render at frontend.
0x1 — Modify your AppServiceProvider
To get started, add this code to AppServiceProvider.php
protected function registerLengthAwarePaginator(){$this->app->bind(LengthAwarePaginator::class, function ($app, $values) {return new class(...array_values($values)) extends LengthAwarePaginator{public function only(...$attributes){return $this->transform(function ($item) use ($attributes) {return $item->only($attributes);});}public function transform($callback){$this->items->transform($callback);return $this;}public function toArray(){return ['data' => $this->items->toArray(),'links' => $this->links(),];}public function links($view = null, $data = []){$this->appends(Request::all());$window = UrlWindow::make($this);$elements = array_filter([$window['first'],is_array($window['slider']) ? '...' : null,$window['slider'],is_array($window['last']) ? '...' : null,$window['last'],]);return Collection::make($elements)->flatMap(function ($item) {if (is_array($item)) {return Collection::make($item)->map(function ($url, $page) {return ['url' => $url,'label' => $page,'active' => $this->currentPage() === $page,];});} else {return [['url' => null,'label' => '...','active' => false,],];}})->prepend(['url' => $this->previousPageUrl(),'label' => 'Previous','active' => false,])->push(['url' => $this->nextPageUrl(),'label' => 'Next','active' => false,]);}};});}
The code above was found on inertiajs/pingcrm
.
0x1 — Testing Pagination
Open a testing route /pages
at routes/web.php
Route::get('/pages', function (Request $request) { return Inertia::render('Welcome', [ 'members' => User::paginate(10) ]);});
Before proceed to testing, remember to clear your route cache using command:
php artisan route:clear
And yeah, the paginated data has successfully passed to frontend:
0x2 — Rendering Frontend
You can now render the data
at frontend:
<div v-for="user in $page.props.members.data" :key="user.id">
<!-- ... -->
</div>
You can also render the links using:
<a v-for="(link,i) in $page.props.members.links" :key="i">
{{link.label}}
</a>
That’s it!
This is actually a very quick walkthrough on the pagination solution. There are a lot of possible customizations such as displaying only the previous
and next
link can be achieved from either from frontend or backend, feel free to comment down below what is your suggestion.
Thank you and stay safe!
😷