Last active
April 1, 2022 17:34
-
-
Save alxmtr/638ed890437f920ba70e5f1b37c76d09 to your computer and use it in GitHub Desktop.
Laravel: List all existing app models.
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 | |
if (! function_exists('list_models')) { | |
/** | |
* Return a list of existing app models. | |
* | |
* @return array | |
*/ | |
function list_models(): array | |
{ | |
$path = app_path('Models'); | |
$files = \File::allFiles($path); | |
return collect($files) | |
->map(fn ($name) => $name->getFilenameWithoutExtension()) | |
->filter(fn ($name) => is_app_model($name)) | |
->values() | |
->toArray(); | |
} | |
} | |
if (! function_exists('is_app_model')) { | |
/** | |
* Check if a given name is an existing app model. | |
* | |
* @return bool | |
*/ | |
function is_app_model(string $name): bool | |
{ | |
return is_subclass_of( | |
"\\App\\Models\\" . $name, | |
\Illuminate\Database\Eloquent\Model::class | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment