jaba
jaba

Reputation: 79

How to fetch data using AJAX LARAVEL with pagination

can you suggest a way on how can I fetch a data using AJAX LARAVEL with pagination? I already have a fetch function using AJAX and it is already working, but I wanted to add a pagination. Thank you in advance.

This is my controller

public function fetchAllCustomer()
{

    $customers = Customer::all();
    return response()->json([
        'customers'=>$customers,
    ]);
}

This is my AJAX function

function fetchstudent() {
      $.ajax({
          type: "GET",
          url: "/fetch-customer",
          dataType: "json",
          success: function (response) {
              // console.log(response);
              $('tbody').html("");
              $.each(response.customers, function (key, item) {
                  $('tbody').append('<tr>\
                      <td>' + item.first_name + '</td>\
                      <td><button type="button" value="' + item.id + '" class="btn btn-primary editbtn btn-sm">Edit</button></td>\
                      <td><button type="button" value="' + item.id + '" class="btn btn-danger deletebtn btn-sm">Delete</button></td>\
                  \</tr>');
              });
          }
      });
  }

Upvotes: 1

Views: 1306

Answers (1)

calebe santana
calebe santana

Reputation: 335

Laravel Docs - Pagination using Eloquent: https://laravel.com/docs/9.x/pagination#paginating-eloquent-results

Instead of:

public function fetchAllCustomer()
{

$customers = Customer::all();
return response()->json([
    'customers'=>$customers,
]);
}

Should be:

    public function fetchAllCustomer()
{
    $customers = Customer::paginate(15);
    // handle your pagination links in AJAX
    $paginationLinks = (string) $customers->links();
    return response()->json([
        'customers'  =>$customers,
        'pagination' => $paginationLinks
    ]);
}

Upvotes: 2

Related Questions