laravelalgolia

How in scout with Algolia make count methods?


Reading how works search method of scout with Algolia driver at https://laravel.com/docs/10.x/scout#searching I wonder can I to implement count and paginate methods

In code like :

if(empty($page)) {
    $returnedData = User::search($key)->get(); // get all data
} else {
    $returnedData = User::search($key)
        ->paginate($rowsPerPage, null, null, $page); // Get only data by $page
    $totalRowsCount = User::search($key) // Get total number of rows to create paginator
        ->getTotalCount(results: $returnedData);
}

I got error :

 Method Laravel\Scout\Builder::getTotalCount does not exist.
  at vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php:112

In which way can I do it ? I am not sure which value must be set into results patrameter...

In docs on prior version https://laravel.su/docs/8.x/scout I found details of this method, but I do not see can it be used under 10(it is not mentioned in 10 docs).

"laravel/framework": "^10.34.2",
"algolia/algoliasearch-client-php": "^3.4",

Thanks in advance!


Solution

  • You don't need to use this method getTotalCount, instead paginate gives you a count of the total results.

    read docs explanation: Pagination

    you can find total count at last in meta (object):

    {
    "data": [
        {
            "id": 1,
            "name": "Eladio Schroeder Sr.",
            "email": "therese28@example.com"
        },
        {
            "id": 2,
            "name": "Liliana Mayert",
            "email": "evandervort@example.com"
        }
    ],
    "links":{
        "first": "http://example.com/users?page=1",
        "last": "http://example.com/users?page=1",
        "prev": null,
        "next": null
    },
    "meta":{
        "current_page": 1,
        "from": 1,
        "last_page": 1,
        "path": "http://example.com/users",
        "per_page": 15,
        "to": 10,
        "total": 10
     }
    }