Conditional Indexing
Control which records get indexed by defining conditions on your Base Model.
The excludeIndex() Method
Section titled “The excludeIndex() Method”By default, every record in your Base Model is indexed. To exclude specific records, override the excludeIndex() method in your model:
class User extends Model{ use Indexable;
public function excludeIndex(): bool { return $this->status === 'banned'; }}When excludeIndex() returns true, the record will be skipped during indexing. This applies to both bulk builds (lens:build) and automatic syncs via observers.
How It Works
Section titled “How It Works”During the build process, ElasticLens calls excludeIndex() on each Base Model record. If it returns true:
- The record is skipped and no index entry is created
- The build state is marked as skipped (not failed)
- If the record was previously indexed, the stale index entry will remain until the next full build or manual cleanup
Cleaning Up Stale Records
Section titled “Cleaning Up Stale Records”When you add or change excludeIndex() conditions on an existing model, previously indexed records that now meet the exclusion criteria will still have index entries. Run a full rebuild to clean them up:
php artisan lens:build UserThe build process will skip excluded records and remove any stale index entries for records that no longer qualify.
Health Check Accounting
Section titled “Health Check Accounting”The lens:health command accounts for excluded records. Skipped records are tracked separately from errors, so your health report accurately reflects the state of your index.
php artisan lens:health User