Data pagination is a common feature on the web. This article will cover implementing it in Vue.js components by fetching data from Laravel API. Let's quickly implement one using the laravel-vue-pagination package. Also, we will cover the "infinite scroll" pagination.
We have installed Laravel with the Laravel Breeze Vue starter-kit preset. Post Model has title
and content
fields, and we seeded 1000 instances.
Install Laravel Vue Pagination Package
First, install the laravel-vue-pagination
package.
npm install laravel-vue-pagination
Make API Resource for Posts Model.
php artisan make:resource PostResource
Then, create an API controller for the Post Model.
app/Http/Controllers/Api/PostController.php
namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller;use App\Http\Resources\PostResource;use App\Models\Post;use Illuminate\Http\Request; class PostController extends Controller{ public function index() { return PostResource::collection(Post::paginate()); }}
We return PostResource
as a response, and the paginate()
method has been called on the Post Model. This way, the response has all the metadata required for pagination.
Example response
{ "data": [ { "id": 1, "title": "Quisquam asperiores cumque aut", "content": "It did so indeed, and much sooner than she had made the whole party at once crowded round her head. Still she went hunting about, and called out 'The Queen! The Queen!' and the baby--the fire-irons.", "created_at": "2023-09-28T14:06:43.000000Z", "updated_at": "2023-09-28T14:06:43.000000Z" } // ... ], "links": { "first": "http://vue-pagination.test/api/posts?page=1", "last": "http://vue-pagination.test/api/posts?page=67", "prev": null, "next": "http://vue-pagination.test/api/posts?page=2" }, "meta": { "current_page": 1, "from": 1, "last_page": 67, "links": [ { "url": null, "label": "« Previous", "active": false }, { "url": "http://vue-pagination.test/api/posts?page=1", "label": "1", "active": true } // ... ], "path": "http://vue-pagination.test/api/posts", "per_page": 15, "to": 15, "total": 1000 }}
Now register the /posts
route in the api.php
file. We can reach it directly by calling the...