Laravel获取模型列表

is it possible with Laravel to get a list of all defined Models into an array in a project so that they could be iterated over in a loop ie

foreach ($models as $model) { 
   echo $model;
}

If all your models are in a single directory, you can list files in this directory and then generate class names based on file names. I'm afraid that's the only option, as Laravel doesn't require declaring models anywhere - creating class is enough. Moreover, listing classes existing in given namespace won't work either, as some models might be implemented, just not loaded.

Try the following code:

<?php
$dir = '/path/to/model/directory';
$files = scandir($dir);

$models = array();
$namespace = 'Your\Model\Namespace\\';
foreach($files as $file) {
  //skip current and parent folder entries and non-php files
  if ($file == '.' || $file == '..' || !preg_match('\.php', $file)) continue;
  $models[] = $namespace . preg_replace('\.php$', '', $file);
}

print_r($models);

I know this answer is pretty late, but could be good if someone is trying to find solution for something similar.

To identify list of classes in my project, I simply defined this small function that helps to get classes at runtime with the help of \File Facade that returns SplFileInfo object array

/**
 * @param $dir
 */
function getClassesList($dir)
{
    $classes = \File::allFiles($dir);
    foreach ($classes as $class) {
        $class->classname = str_replace(
            [app_path(), '/', '.php'],
            ['App', '\\', ''],
            $class->getRealPath()
        );
    }
    return $classes;
}

Usage of above function in Laravel

$classes = getClassesList(app_path('Models'));
// assuming all your models are present in Models directory