Last active
January 23, 2021 11:44
-
-
Save bayareawebpro/1fd55a797f5c8a6db734c24ac43cf41f to your computer and use it in GitHub Desktop.
Automatic MorphMap for Laravel Models within a Namespace
This file contains 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 | |
$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