We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
When you use Laravel Scout, every time you save your model, it will be synced to the search index. In some cases, this is not the behaviour you want.
In our use-case for example, we are using Laravel Scout to enable full-text search in PDF files. The issue we ran into was that the operation to make a PDF searchable is an expensive operation which takes some time and shouldn't happen upon every save of a document.
In our scenario, there are only two properties of a document which are searchable: the textual content and the name of the document. All other properties are not searchable. If you change the ones which are not searchable, the search indexing should not be triggered.
To accomplish this, we first started with disabling the automatic syncing for scout. To do so, add the following to your AppServiceProvider
:
namespace App\Providers;
use App\Models\Document;
class AppServiceProvider extends ServiceProvider
{
use CreatesPrivateKey;
public function boot(): void
{
Document::disableSearchSync();
}
}
To then make the search indexing conditional, we can add this to the model:
namespace App\Models;
class Document extends Model
{
public static function boot(): void
{
parent::boot();
self::saved(function (self $document) {
if ($document->wasChanged(['name', 'text'])) {
$document->searchable();
}
});
}
}
Now, only when you change the name or text of a document, the search index will be updated.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.