I've configured Laravel Scout and can use ::search()
on my models.
The same models also use SoftDeletes.
How can I combine the ::search()
with withTrashed()
?
The code below does not work.
MyModel::search($request->input('search'))->withTrashed()->paginate(10);
The below does work but does not include the trashed items.
MyModel::search($request->input('search'))->paginate(10);
Update 1 I found in the scout/ModelObserver that deleted items are made unsearchable. Which is a bummer; I wanted my users to be able to search through their trash.
Update 2
I tried using ::withoutSyncingToSearch,
as suggested by @camelCase, which I had high hopes for, but this also didn't work.
$model = MyModel::withTrashed()->where('slug', $slug)->firstOrFail();
if ($model->deleted_at) {
$model->forceDelete();
} else {
MyModel::withoutSyncingToSearch(function () use ($model) {
$model->delete();
});
}
This caused an undefined offset when searching for a deleted item. By the way, I'm using the TNTSearch driver for Laravel Scout. I don't know if this is an error with TNTSearch or with Laravel Scout.
I've worked out a solution to your issue. I'll be submitting a
pull request
forScout
to hopefully get it merged with the official package.This approach allows you to include soft deleted models in your search:
To only show soft deleted models in your search:
You need to modify 3 files:
Builder.php
In
laravel\scout\src\Builder.php
add the following:Engine.php
In
laravel\scout\src\Engines\Engine.php
modify the following:And finally, you just need to modify your relative search engine. I'm using Algolia, but the
map
method appears to be the same forTNTSearch
.AlgoliaEngine.php
In
laravel\scout\src\Engines\AlgoliaEngine.php
modify themap
method to match theabstract
class we modified above:TNTSearchEngine.php
Let me know how it works.
NOTE: This approach still requires you to manually pause syncing using the
withoutSyncingToSearch
method while deleting a model; otherwise the search criteria will be updated withunsearchable()
.