Home > Enterprise >  How to fetch data using AJAX LARAVEL with pagination
How to fetch data using AJAX LARAVEL with pagination

Time:03-09

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   '" >Edit</button></td>\
                      <td><button type="button" value="'   item.id   '" >Delete</button></td>\
                  \</tr>');
              });
          }
      });
  }

CodePudding user response:

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
    ]);
}
  • Related