Calculate Sum with Pagination

How to calculate the sum of all records when you have only the PAGINATED collection? Do the calculation BEFORE the pagination, but from the same query.

1// How to get sum of post_views with pagination?
2$posts = Post::paginate(10);
3// This will be only for page 1, not ALL posts
4$sum = $posts->sum('post_views');
5 
6// Do this with Query Builder
7$query = Post::query();
8// Calculate sum
9$sum = $query->sum('post_views');
10// And then do the pagination from the same query
11$posts = $query->paginate(10);

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord