Integrations / Frameworks / Laravel / Import Into Algolia

Import Into Algolia

Import

When setting up Scout Extended, you probably have existing data that you would like to import. There is an scout:import Artisan command to import data:

$
php artisan scout:import

The searchable classes are automatically detected, but feel free to specify the searchable class to import:

$
php artisan scout:import "App\Article"

Need to import data in production? Take a look at the section Zero Downtime Reimports.

Flushing and clearing

The scout:flush Artisan command is the easiest way to flush the data from Algolia’s index:

$
php artisan scout:flush

Keep data in sync

Every time you modify a model, Laravel emits an event. Scout is listening for that event, informing your app to make an HTTP call to Algolia to update its index.

You don’t have anything else to do, use your searchable class the way you usually would do. For example, in a controller you may have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ArticleController extends Controller
{
    /**
     * Update the given article.
     *
     * @param  Request  $request
     * @param  string  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        Article::find(request('id'));

        $article->title = request('title');

        /**
         *  Scout will automatically persist the
         *  changes to your Algolia search index.
         */
        $article->update();
    }
}

It’s important to note that the data will not be synced when using mass assignment methods since the saved and updated events won’t be dispatched:

1
2
3
4
5
6
/**
 *  Here, Scout will NOT persist the
 *  changes to your Algolia search index.
 */
Article::where('id', request('id'))
    ->update(['title' => request('title')]);

Conditional Sync

Sometimes you may want to sync a searchable class only when something else is true. To accomplish this, you may define your own shouldBeSearchable method on your searchable class:

1
2
3
4
5
6
7
8
9
class Article extends Model
{
    use Searchable;
    
    public function shouldBeSearchable()
    {
        return $this->isPublished();
    }
}

Pause indexing

Scout documentation shows a nice way to modify a searchable model without triggering indexing calls using a callback.

There is also a static method you can use to disable/enable syncing. This is especially useful if you’re going to do many SQL queries to modify content. Once it’s done, you can sync what you’ve modified manually.

For example, in your DatabaseSeeder class:

1
2
3
4
5
6
7
8
9
10
11
12
13
class DatabaseSeeder extends Seeder
{
    public function run()
    {
        Article::disableSearchSyncing();

        $this->call(ArticleSeeder::class);

        Article::all()->searchable();

        Article::enableSearchSyncing();
    }
}

Did you find this page helpful?