Skip to content

Instantly share code, notes, and snippets.

@alxmtr
Last active April 1, 2022 17:34
Show Gist options
  • Save alxmtr/638ed890437f920ba70e5f1b37c76d09 to your computer and use it in GitHub Desktop.
Save alxmtr/638ed890437f920ba70e5f1b37c76d09 to your computer and use it in GitHub Desktop.
Laravel: List all existing app models.
<?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