Skip to content

Base Model Observers

Your Base Model is observed for saves and deletions out of the box. When the base model is deleted, its Index Model goes with it.

When your fieldMap() includes embedded fields, the related models are observed too.

A save or delete on ProfileStatus triggers a chain: find the related Profile, then User, then rebuild that user’s index.

One catch: embedded model observers are only loaded when the base model class has been referenced. You need to touch the User model first:

//This alone will not trigger a rebuild
$profileStatus->status = 'Unavailable';
$profileStatus->save();
//This will
new User::class
$profileStatus->status = 'Unavailable';
$profileStatus->save();

If you want ElasticLens to observe an embedded model independently (without needing to reference the base model first), use HasWatcher:

1. Add the HasWatcher Trait to the Embedded Model:

Section titled “1. Add the HasWatcher Trait to the Embedded Model:”
App\Models\ProfileStatus.php
use PDPhilip\ElasticLens\HasWatcher;
class ProfileStatus extends Eloquent
{
use HasWatcher;
config/elasticlens.php
'watchers' => [
\App\Models\ProfileStatus::class => [
\App\Models\Indexes\IndexedUser::class,
],
],

The watcher maps the observed model to the index model that should rebuild when it changes.

If you don’t want the Base Model observed at all (you’ll handle syncing manually), disable it:

class IndexedUser extends IndexModel
{
protected $baseModel = User::class;
protected $observeBase = false;