Oh man, I've been here haha. The issue is that your toSearchableArray() method is trying to access relationships that aren't properly loaded when Scout processes the models during import. Even though you have makeSearchableUsing(), there might be timing or eager loading issues.
A few questions to narrow this down:
- Are you seeing any errors during the import process?
- Do the
creatorandupdaterrelationships work correctly outside of Scout? - What does
HasUserStampstrait look like - specifically the relationship definitions?
Debugging steps:
Check what's actually being indexed:
// Add this temporarily to toSearchableArray() for debugging the issue
public function toSearchableArray()
{
\Log::info('Indexing user: ' . $this->id, [
'roles_loaded' => $this->relationLoaded('roles'),
'creator_loaded' => $this->relationLoaded('creator'),
'updater_loaded' => $this->relationLoaded('updater'),
'roles_count' => $this->roles->count(),
'creator_exists' => $this->creator ? 'yes' : 'no',
]);
return [
// ... your existing array
];
}
More explicit relationship loading:
public function makeSearchableUsing(Collection $models): Collection
{
return $models->load([
'roles:id,name', // Be specific about what you need!
'creator:id,name',
'updater:id,name'
]);
}
Alternative approach - handle null cases:
public function toSearchableArray()
{
// Ensure relationships are loaded
$this->loadMissing(['roles', 'creator', 'updater']);
return [
'id' => (string) $this->id,
'name' => $this->name,
'email' => $this->email,
'roles' => $this->roles->pluck('name')->toArray(),
'role' => $this->roles->first()?->name,
'status' => $this->status ? 'Active' : 'Inactive',
'created_at' => $this->created_at->timestamp,
'created_by' => $this->creator?->name,
'updated_at' => $this->updated_at->timestamp,
'updated_by' => $this->updater?->name,
'organization_id' => $this->organization_id,
];
}
Can you check the debug logs first to see what relationships are actually loaded during indexing?