Laravel and Vue.js: Pagination and Infinite Scroll Examples

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.

Vue Pagination


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...

The full tutorial [7 mins, 1351 words] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 52 courses (952 lessons, total 46 h 42 min)
  • 77 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials