Skip to content

Commit 5c75b61

Browse files
committed
Add paginator service for pagination logic
1 parent a029b94 commit 5c75b61

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace Ivy\Shared\Infrastructure\Service;
4+
5+
use Illuminate\Database\Eloquent\Builder;
6+
use Symfony\Component\HttpFoundation\Request;
7+
8+
class PaginationService
9+
{
10+
public function paginate(
11+
Builder $query,
12+
Request $request,
13+
int $perPage = 25
14+
): array {
15+
16+
$page = max(1, (int) $request->query->get('page', 1));
17+
18+
$total = (clone $query)->count();
19+
20+
$items = $query
21+
->offset(($page - 1) * $perPage)
22+
->limit($perPage)
23+
->get();
24+
25+
$lastPage = (int) ceil($total / $perPage);
26+
27+
return [
28+
'data' => $items,
29+
'meta' => [
30+
'current_page' => $page,
31+
'per_page' => $perPage,
32+
'total' => $total,
33+
'last_page' => $lastPage,
34+
'has_next' => $page < $lastPage,
35+
'has_prev' => $page > 1,
36+
],
37+
];
38+
}
39+
}

0 commit comments

Comments
 (0)