Skip to content

Instantly share code, notes, and snippets.

@chasecmiller
Created September 13, 2021 04:18
Show Gist options
  • Save chasecmiller/31911785c8a058e1a3d17cf387cc9c38 to your computer and use it in GitHub Desktop.
Save chasecmiller/31911785c8a058e1a3d17cf387cc9c38 to your computer and use it in GitHub Desktop.
A simple way to get all models in your app space in Laravel.
$files = [];
foreach ([
app_path('Models/*.php'),
app_path('*.php'),
] as $path) {
$folder = dirname($path);
if (!file_exists($folder) || !is_dir($folder)) {
continue;
}
$files = array_merge($files, glob($path));
}
$models = [];
foreach ($files as $file) {
$fp = fopen($file, 'r');
$class = $buffer = '';
$i = 0;
while (!$class) {
if (feof($fp)) break;
$buffer .= fread($fp, 512);
$tokens = token_get_all($buffer);
if (strpos($buffer, '{') === false) continue;
for (; $i < count($tokens); $i++) {
if ($tokens[$i][0] === T_CLASS) {
for ($j = $i + 1; $j < count($tokens); $j++) {
if ($tokens[$j] === '{') {
if (preg_match('#namespace (.*?);#', substr($buffer, 0, $tokens[$i + 2][0]), $namespace)) {
$class = '\\' . $namespace[1] . '\\' . $tokens[$i + 2][1];
} else {
$class = $tokens[$i + 2][1];
}
}
}
}
}
}
if (
$class
&& class_exists($class)
&& is_subclass_of($class, \Illuminate\Database\Eloquent\Model::class)
) {
$models[] = $class;
}
}
// Now $models is a list of class names, with their namespace.
foreach($models as $class) {
$model = new $class();
echo $model->getTable();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment