The issue you're experiencing is due to the fact that the toSearchableArray method is not being called after the related Category model is updated. This is because the searchable method is only being triggered when the Seed model itself is updated, not when the related Category model is updated.
To ensure that the Seed model is re-indexed in Meilisearch whenever the related Category model is updated, you need to listen for changes on the Category model and then trigger the searchable method on the related Seed models.
Here's a solution to achieve this:
- Add an observer to the
Categorymodel to listen for updates. - In the observer, re-index the related
Seedmodels.
First, create an observer for the Category model:
// app/Observers/CategoryObserver.php
namespace App\Observers;
use App\Models\Category;
class CategoryObserver
{
public function updated(Category $category)
{
// Re-index all related Seed models
foreach ($category->seeds as $seed) {
$seed->searchable();
}
}
}
Next, register the observer in your AppServiceProvider:
// app/Providers/AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Models\Category;
use App\Observers\CategoryObserver;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Category::observe(CategoryObserver::class);
}
}
Finally, ensure that you have a relationship defined in the Category model to get the related Seed models:
// app/Models/Category.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function seeds()
{
return $this->hasMany(Seed::class);
}
}
With this setup, whenever a Category model is updated, the updated method in the CategoryObserver will be triggered, which will then re-index all related Seed models in Meilisearch.
This should ensure that the category.name and category.slug fields in the search index are always up to date.