Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Using Algolia in Laravel

Algolia is a hosted service that makes advanced searching very easy. It’s well documented and lightning quick. You can see some impressive examples on their site. Artisans probably know that Jeffrey Way recently published a series on Algolia.

Earlier this year I made a package to easily work with a searchindex in Laravel. Basically it provides:

  • an interface that makes your objects searchable
  • some easy to use functions to put those objects into the search index
  • a function to retrieve search results from the index

The only supported index was Elasticsearch. I’ve now added support for Algolia to that package. It makes working with Algolia a cinch. Sure, there’s the official Laravel integration, and it probably works well, but it felt a bit too “heavy” for my needs.

Using my package you just got to implement the Searchable-interface on an object you want to index. That object can be an Eloquent model, but you really can use it on any class you like. Once the interface is implemented these methods can be used:

//$product is an object that implements the Searchable interface

//adding or updating something to the index

//removing something from the index

SearchIndex::getResults('my favorite product');

To perform more advanced queries an array may be passed to the getResults-function. Read the official Algolia documentation to learn what’s possible.

You’ll find some more information on the package on GitHub:

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.