Created
August 21, 2019 14:46
-
-
Save mattdfloyd/22b094f808634a79c73ce6692cc22096 to your computer and use it in GitHub Desktop.
Searchable cascade via dot notation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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