scout: orderBy doesn't work

Hi there,

I’m using scout with algolia to index a large database of products, however when trying to sort the results, i’m not getting the desired results.

$products = Product::search('')
                ->orderBy('name', 'asc')
                ->paginate();

Anything i’m missing for this to return results ordered by name?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 18 (8 by maintainers)

Most upvoted comments

Hi there,

I’m using scout with algolia to index a large database of products, however when trying to sort the results, i’m not getting the desired results.

$products = Product::search('')
                ->orderBy('name', 'asc')
                ->paginate();

Anything i’m missing for this to return results ordered by name?

Got it to work by wrapping it into a query:

$products = Product::search('')->query(function($q) {
                $q->orderBy('name', 'asc')
                })->paginate();

nailed it, thanks!

Hi @calvinmuller,

Algolia doesn’t not allow ordering at query time. The data are ordered while being indexed, which makes the query much faster. You will need to create a replicas in your Algolia dashboard and sort this index by name. Please have a look at: https://www.algolia.com/doc/tutorials/indexing/ranking/how-to-sort-the-results-with-a-specific-attribute/index.html

Then with Scout, you can use the within method to query the desired index.

$products = Product::search('')
                ->within('products_by_name')
                ->paginate();

That’s not good. The solution is just use the same algorith that I have done for Scout Extended: After resolving the models from the database, just order them using the $ids of Algolia.