Skip to content

Base Model Observers

By default, the Base Model will be observed for changes (saves) and deletions. When the Base Model is deleted, the corresponding Index Model will also be deleted, even in cases of soft deletion.

When you define a fieldMap() with embedded fields, the related models are also observed. For example:

A save or delete action on ProfileStatus will trigger a chain reaction, fetching the related Profile and then User, which in turn initiates a rebuild of the index for that user record.

However, to ensure these observers are loaded, you need to reference the User model explicitly:

//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, you can use the HasWatcher trait.

This allows you to define a watcher for a specific related model which will trigger a rebuild of a specific index model.

1. Add the HasWatcher Trait to Embedded Model:

Section titled “1. Add the HasWatcher Trait to Embedded Model:”
App\Models\ProfileStatus.php
use PDPhilip\ElasticLens\HasWatcher;
class ProfileStatus extends Eloquent
{
use HasWatcher;

2. Define the Watcher in the elasticlens.php Config File:

Section titled “2. Define the Watcher in the elasticlens.php Config File:”
config/elasticlens.php
'watchers' => [
\App\Models\ProfileStatus::class => [
\App\Models\Indexes\IndexedUser::class,
],
],

The watchers definition maps the watched model to trigger which index model to rebuild.

If you want to disable the automatic observation of the Base Model, include the following in your Index Model:

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