How to combine tag and algolia search in Laravel

  algolia, eloquent, laravel, php, search

I have a Laravel 7 app that uses Spatie’s tagging package, and also Algolia search using their standard library via its stock Laravel Scout integration. The two search mechanisms come down to this for the tags:

$items = Item::withAllTags(

This apparently returns an Eloquent "scope", not a builder or collection, which I don’t quite understand.

Then this for Algolia:

$items = Item::search($request->input('query'));

This returns a query builder, and I can call get() on it to resolve the actual items.

What I want to do is combine the two, so that I can get a set of search results that represents the intersection of these two result sets. Ideally I’d like to do the tags first as it’s local and probably faster, and then get Algolia to search the result set.

I’ve tried to use the intersect builder helper, but that breaks my use of paginate on search results because that’s is a builder feature, not a collection feature. I then found Spatie’s collection macros, which adds pagination to collections, however, it doesn’t seem to work as expected and makes the pagination links normally created by the Blade’s {{ $items->links() }} render to nothing.

How can I best do this?

Source: Laravel

Leave a Reply