Laravel Scout: Standard way to use algolia search with your Laravel application

Laravel Scout: Standard way to use algolia search with your Laravel application

May 29, 2019 / Ramesh Mhetre

During software development we often needs to implement search functionality. Some times, you might need to implement simple search in the specific dataset or sometimes it is more complex search with multiple large datasets with pattern & text search.

You can always build your own little search engine by querying on your database. This is approach has many disadvantages over using some full fledge search engine like, you might end up putting huge load on your database, search logic might get really complex with large dataset and queries can be really slow for huge data.

That is why we have a different approach where we use right thing for right job. Search engines like Algolia, Elasticsearch or Solr Search are made to do this specific job for you.

Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.

Laravel Scout has official driver for algolia, however they have a support write custom driver for your need. In Fact there are already some drivers on github for famous search engine.

Laravel scout installation

First, install Scout via composer:

composer require laravel/scout

After installing Scout, you should publish the Scout configuration using the vendor:publish Artisan command. This command will publish the scout.php configuration file to your config directory:

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

Finally, add the Laravel\Scout\Searchable trait to the model you would like to make searchable. This trait will register a model observer to keep the model in sync with your search driver:

<?php

namespace App;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Searchable;
}

Laravel Scout Driver Installation

Since we are using the Algolia driver, we should configure our Algolia id and secret credentials in our config/scout.php configuration file. We will also need to install the Algolia PHP SDK via the Composer package manager:

composer require algolia/algoliasearch-client-php:^2.2

Laravel Scout Data Indexing to Algolia

In order to use algolia search, we first need to index the data to the search engine. Doing it with laravel is dead simple.

Model Configuration

Each Eloquent model is synced with a given search "index", which contains all of the searchable records for that model. In other words, you can think of each index like a MySQL table. By default, each model will be persisted to an index matching the model's typical "table" name. Typically, this is the plural form of the model name; however, you are free to customize the model's index by overriding the searchableAs method on the model:

<?php

namespace App\Models;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Searchable;

    public function searchableAs()
    {
        return 'posts_index';
    }
}

Configuring Searchable Data

By default, the entire toArray form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the toSearchableArray method on the model:

<?php

namespace App\Models;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Searchable;
    public function toSearchableArray()
    {
        $array = $this->toArray();

        $data = [
            'id' => $array['id'],
            'slug' => $array['slug'],
            'title' => $array['title'],
            'excerpt' => $array['excerpt'],
            'body' => $array['body'],
            'featured_image' => $array['featured_image'],
        ];
        
        return $data;
    }
}

Laravel Scout Batch Import

If you are installing Scout into an existing project, you may already have database records you need to import into your search driver. Scout provides an import Artisan command that you may use to import all of your existing records into your search indexes:

php artisan scout:import "App\Models\Post"

The flush command may be used to remove all of a model's records from your search indexes:

php artisan scout:flush "App\Post"

This is all the basics, you can do more advanced stuff like querying specific result set & indexing them, removing indexed data, pause indexing, conditionally index data. You can find more details here.


Built Your Search With Algolia

Now we have already indexed our data to algolia search, you can head over to your algolia account & should see the data.

Now is the time to build actual search on your website.

Algolia has their official clients/SDK's for all famous tech stack. You can choose wisely whatever you prefers.

Laravel Scout Searching

You may begin searching a model using the search method. The search method accepts a single string that will be used to search your models. You should then chain the get method onto the search query to retrieve the Eloquent models that match the given search query:

$posts = App\Models\Post::search('Laravel')->get();

Since Scout searches return a collection of Eloquent models, you may even return the results directly from a route or controller and they will automatically be converted to JSON:

use Illuminate\Http\Request;

Route::get('/search', function (Request $request) {
    return App\Models\Post::search($request->search)->get();
});

If you would like to get the raw results before they are converted to Eloquent models, you should use the raw method:

$posts = App\Models\Post::search('Laravel')->raw();

Likewise you can do things like adding where clause, handling soft deletes, pagination, working on raw data. You can find all details in here.


Similar Articles

Compiling assets with Laravel Mix

Compiling assets with Laravel Mix

Laravel Mix provides a fluent API for defining Webpack build steps
Read more...
Using Laravel's Eloquent ORM Efficiently

Using Laravel's Eloquent ORM Efficiently

Tips & tricks for Laravel's Eloquent ORM.
Read more...
Use ReactJS with your Laravel application

Use ReactJS with your Laravel application

The standard way to start using ReactJS with your laravel application.
Read more...