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:

$document = Document::withoutSyncingToSearch(function () use ($fileName, $url) {
    $document = Document::create([
        'company_id' => $this->company->id,
        'name' =>  $fileName,
    ]);

    // This does not trigger the search indexing
    $document->save();

    DocumentVersion::create([
        'document_id' => $document->id,
        'name' => $document->name,
        'url' => $document->url,
    ]);

}

// This does trigger the search indexing
$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: