Skip to content

Instantly share code, notes, and snippets.

@bayareawebpro
Last active January 23, 2021 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayareawebpro/1fd55a797f5c8a6db734c24ac43cf41f to your computer and use it in GitHub Desktop.
Save bayareawebpro/1fd55a797f5c8a6db734c24ac43cf41f to your computer and use it in GitHub Desktop.
Automatic MorphMap for Laravel Models within a Namespace
<?php
$namespace = 'App\Models';
$models = array_filter(get_declared_classes(), function($index) use ($namespace) {
return strpos($index, $namespace) === 0;
});
$morphMap = array();
foreach($models as $class){
$mapName = snake_case(str_plural(class_basename($class)));
$morphMap[$mapName] = $class;
}
\Illuminate\Database\Eloquent\Relations\Relation::morphMap($morphMap);
dd($morphMap);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment