Skip to content

Instantly share code, notes, and snippets.

@mattdfloyd
Created August 21, 2019 14:46
Show Gist options
  • Save mattdfloyd/22b094f808634a79c73ce6692cc22096 to your computer and use it in GitHub Desktop.
Save mattdfloyd/22b094f808634a79c73ce6692cc22096 to your computer and use it in GitHub Desktop.
Searchable cascade via dot notation
<?php
use Illuminate\Support\Collection;
use Laravel\Scout\Searchable;
abstract class Cascade
{
protected $models = [
// Organization::class => ['users']
];
public function getModels() {
return $this->models;
}
public static function boot() {
foreach ((new static)->getModels() as $class => $touches) {
$class::saved(function ($instance) use ($touches) {
foreach ($touches as $touched) {
Collection::make(explode('.', $touched))->reduce(function ($relation, $touched) {
return tap($relation->$touched, function ($touched) {
Collection::wrap($touched)->pipe(function ($touched) {
if (! in_array(Searchable::class, class_uses($touched->first()))) {
return new Collection;
}
return $touched;
})->each->searchable();
});
}, $instance);
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment