#database #development #laravel #php

When you use Laravel Scout for full-text search, you'll probably know that it triggers a reindex of a model every time you call the save method.

In my scenario, this wasn't exactly what I wanted to happen. The idea is that the searchable content of my model depends on a relationship which might not exist yet.

To get around this, you can temporarily pause the indexing by using the withoutSyncingToSearch method.

Our code ended up looking something like this:

 1$document = Document::withoutSyncingToSearch(function () use ($fileName, $url) {
 2    $document = Document::create([
 3        'company_id' => $this->company->id,
 4        'name' =>  $fileName,
 5    ]);
 6
 7    // This does not trigger the search indexing
 8    $document->save();
 9
10    DocumentVersion::create([
11        'document_id' => $document->id,
12        'name' => $document->name,
13        'url' => $document->url,
14    ]);
15
16}
17
18// This does trigger the search indexing
19$document->save();

The documentation explains the method like this:

Sometimes you may need to perform a batch of Eloquent operations on a model without syncing the model data to your search index. You may do this using the withoutSyncingToSearch method. This method accepts a single closure which will be immediately executed. Any model operations that occur within the closure will not be synced to the model's index: