Fabian
Fabian

Reputation: 1846

Laravel Scout check if index exists

I can't find documentation on how to check with Laravel Scout if an index exists or not.

I'm using it with meilisearch. My models have the Searchable trait.

This is how I want to access the index and check for search results:

$tasks = Task::search(
  query: trim($query) ?? '',
)->take(self::NUMBER_OF_SEARCHRESULTS_PER_MODEL)->get();

What I get is 'MeiliSearch \ Exceptions \ ApiException Index tasks not found.'

Another weird behavior, even though I execute scout:import "App\Models\Task" before, and it tells me that all records have been imported, meilisearch is not creating the index, if there are no records in the DB.

Therefor the above code results in the exception.

What I'd like to do now to prevent that, is something like this:

$tasksScoutBuilder = Task::search(
  query: trim($query) ?? '',
);

$tasks = ($tasksScoutBuilder->indexExists()) ? $tasksScoutBuilder->take(self::NUMBER_OF_SEARCHRESULTS_PER_MODEL)->get() : collect(); 

How can I check if the index for the model exists or not?

Upvotes: 0

Views: 1188

Answers (1)

Daniel
Daniel

Reputation: 11

Before anything you should configuration model.you can overriding the searchableAs method on the model,if the index does not exist,Laravel throw exception like index_not_found_exception, for ex

public function searchableAs()
    {
        return 'posts_index';
    }

Upvotes: 0

Related Questions