I'm trying to create a pagination system with Laravel. On the backend side I'm returning a JSON response like this:
if(isset($request->myDate)) {
$request->validate([
'myDate' => 'required|date',
]);
$start_date = $request->get('myDate');
$end_date = Carbon::now();
$my_tickets = Ticket::where('admin_id', Auth::user()->id)->whereBetween('updated_at', [$start_date, $end_date])->with(['getAdmin'])->paginate(10);
}
return json_encode($my_tickets);
On the front-end side, I'm using an AJAX request to display the rows. My question now is how to implement the pagination system. Is there any inbuilt function from Laravel or third-party components to simplify this? Do I have to build the front end on my own? I can't access the $var->links() since it's not the same function as returning the view.
Best Regards
In the frontend Response, you can get the page number, a total number of counts, per page, etc. if you want to use custom ajax pagination then use the following code in ajax.
var page = ''
var count = 0;
if (response.total > response.perPage) {
if (response.page != 1) {
page += '<li class="page-item"><a class="page-link" data-page="' + (response.page - 1) + '" href="#">' + 'Previous' + '</a></li>'
}
for (i = response.page; i <= response.totalPage; i++) {
count++;
if (response.page == i) {
page += '<li class="page-item active"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>'
} else {
page += '<li class="page-item"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>'
}
if (count == 10) break;
}
$('.number-of-show').append(' Showing ' + ((response.perPage * (response.page - 1)) + 1) + ' to ' + response.perPage * response.page + ' of ' + response.total);
$('.pagination').append(page);
}
In controller
$page = '';
if (!empty($data['page'])) {
$page = $data['page'];
}
$params['perPage'] = 500;
$params['offset'] = ($page - 1) * $params['perPage'];
$withdrawRequestLists = $paramsData['data'];
$total = $paramsData['total'];
$totalPage = ceil($total / $params['perPage']);