This repository has been archived by the owner on May 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Indexes settings using model
Clémentine Urquizar edited this page Feb 1, 2021
·
5 revisions
First create a command file:
php artisan make:command ScoutSync
The content of app/Console/Commands/ScoutSync.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Laravel\Scout\EngineManager;
use Laravel\Scout\Searchable;
use MeiliSearch\Client;
class ScoutSync extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'scout:sync {model? : Class name of model to update settings}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Sync your configuration with meilisearch';
/**
* The meilisearch client.
*
* @var Client
*/
private $client;
public function __construct()
{
parent::__construct();
$this->client = app(EngineManager::class)->driver('meilisearch');
}
/**
* Execute the console command.
*/
public function handle(): void
{
if ($namespace = $this->argument('model')) {
$model = new $namespace;
$this->syncModel($model);
return;
}
$this->syncAll();
}
private function syncModel($model): void
{
if ($this->hasSettings($model)) {
$this->updateSettings($model);
}
}
private function syncAll(): void
{
collect(scandir(app_path('Models')))->each(
function ($path) {
if ($path === '.' || $path === '..') {
return true;
}
$namespace = 'App\Models\\' . substr($path, 0, -4);
$model = new $namespace;
$this->syncModel($model);
}
);
}
private function updateSettings($model): void
{
$index = $this->client->index($model->searchableAs());
collect($model->meilisearchSettings)->each(
function ($value, $key) use ($index) {
$status = $index->{$key}($value);
$this->line("{$key} has been updated, updateId: {$status['updateId']}");
}
);
}
private function hasSettings($model): bool
{
return in_array(Searchable::class, class_uses($model)) && property_exists($model, 'meilisearchSettings');
}
}
Then in your model you can add a new class property with the configuration
public $meilisearchSettings = [
'updateAttributesForFaceting' => [
'title',
'genres',
],
'updateSynonyms' => [
'movie' => ['video'],
'video' => ['movie'],
],
'updateSearchableAttributes' => ['title']
];
Here is the list of all available settings:
- updateSynonyms
- updateStopWords
- updateAttributesForFaceting
- updateRankingRules
- updateDistinctAttribute
- updateSearchableAttributes
- updateSearchableAttributes
More information on how to configure your settings Meilisearch Settings