How to get the total count of products in Shopify GraphQL API in Laravel?

332 Views Asked by At

I don't know how to get the total count of my products in shopify graphql. I need to get the total count of my products in shopify because I am creating a pagination with numbers. As of now I created cursor-based pagination which is the next and previous buttons but I want to add numbers of pages.

I tried to remove the variable $numberProduct, I am using this to fetch only of number of products (9) per page and now I directly put the first: 100 in my query and the numbers or array of pages is showing but all of my products is showing in my product page/blade view because I declare it in my query which is the 100.

This is my logic on how to get the numbers of pages: // Calculate total number of products $totalProducts = count($data['data']['products']['edges']);

            // Calculate total number of pages
            $totalPages = ceil((int)$products / $numProducts);

            // Generate an array of page numbers
            $pageNumbers = range(1, $totalPages);

Output: 1 number of pages

This is where I try to remove the variable $numberProduct and declare directly to my query first: 100: // Calculate total number of products $totalProducts = count($data['data']['products']['edges']);

            // Calculate total number of pages
            $totalPages = ceil((int)$totalProducts / 9);

            // Generate an array of page numbers
            $pageNumbers = range(1, $totalPages); 

Output: 12345678 number of pages which is correct

2

There are 2 best solutions below

2
David Lazar On

You cheat and skip the GQL and just ask the products endpoint for the count. Same as asking the RestAPI for the count. Instant and easy. There is no analog in GQL for that. GQL works off of cursors, arguably the much faster way of paging through products, but there is no totalCount with GQL.

0
Yousha Aleayoub On

This is just an idea, I'm not sure if it will work:

$api = ShopifyApp::api();
// Define the query.
$query = 
'{
   shop
   {
      products(first: 1)
      {
         totalCount
      }
   }
}';
$response = $api->graph(GraphqlEnum::ADMIN_API, new GraphqlValue($query));
// Total count of products.
$totalCount = $response['data']['shop']['products']['totalCount'];