Farshad
Farshad

Reputation: 2000

How to make pagination for Laravel resource API

I have a model that I paginate like this:

$reserve = PropertyCalendar::paginate(1);
return new ReserveResource($reserve);

I also made an API that responds with resource, and in Vue component I'll calling it with axios.get.

public function toArray($request)
{
  return parent::toArray($request);
}

Here is the API response:

{
  "current_page": 1,
  "data": [
    {
      "id": 1,
      "property_id": 1,
      "user_id": 1,
      "payable_price": 11,
      "reserve_start": "2019-03-30 00:00:00",
      "reserve_end": "2019-04-01 00:00:00",
      "created_at":null,
      "updated_at":null
    }
  ],
  "first_page_url": "http:\/\/localhost:8000\/api\/reserve?page=1",
  "from": 1,
  "last_page": 2,
  "last_page_url": "http:\/\/localhost:8000\/api\/reserve?page=2",
  "next_page_url": "http:\/\/localhost:8000\/api\/reserve?page=2",
  "path": "http:\/\/localhost:8000\/api\/reserve",
  "per_page": 1,
  "prev_page_url": null,
  "to": 1,
  "total": 2
}

Now I want to know how can I make pagination for it, I can't make it with traditional Laravel pagination as it is in Vue component.

loadReserves() {
  axios.get("../api/reserve", {
    params: {
      commentId: this.comment_id
    }
  }).then((response) => (this.comments = response.data.data));
},

Now I am showing data but I want to paginate it like what in the API.

Upvotes: 0

Views: 707

Answers (2)

Cloud Soh Jun Fu
Cloud Soh Jun Fu

Reputation: 1512

This is some example with bootstrap showing how you can use Laravel pagination with Vue.js

Example.

<ul class="pagination">
  <li class="page-item" :class="{disabled: response.current_page === 1}">
    <a class="page-link" @click="previous">Previous</a>
  </li>
  <li 
      v-for="number in response.last_page"
      class="page-item"
      :class="{active: response.current_page === number}"
      >
    <a class="page-link" @click="navigateTo(number)">{{ number }}</a>
  </li>
  <li class="page-item" :class="{disabled: response.current_page === response.last_page}">
    <a class="page-link" @click="next">Next</a>
  </li>
</ul>

Upvotes: 0

Vlad Visinescu
Vlad Visinescu

Reputation: 747

If using bootstrap is not a problem for your use case, I'd recommend using this vue plugin.

I am using it myself with great results.

https://github.com/gilbitron/laravel-vue-pagination

Upvotes: 1

Related Questions