TIP 04 / 08

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.

code
// Calculate the total post views alongside pagination.
$posts = Post::paginate(10);
// This sums only the records on the current page.
$sum = $posts->sum('post_views');

// Use the query builder to calculate the total first.
$query = Post::query();
// Calculate the total before pagination.
$sum = $query->sum('post_views');
// Paginate the same query after calculating the total.
$posts = $query->paginate(10);