Skip to content

Instantly share code, notes, and snippets.

@blueridgemountains1
Last active September 8, 2022 17:04
Show Gist options
  • Save blueridgemountains1/f47b56a5d057c7d787fc1815ef79fb95 to your computer and use it in GitHub Desktop.
Save blueridgemountains1/f47b56a5d057c7d787fc1815ef79fb95 to your computer and use it in GitHub Desktop.
Laravel - PHP - Get All Models Classes - (2022)
<?php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;
use ReflectionClass;
function getAllModels(): Collection
{
$composer = json_decode(file_get_contents(base_path('composer.json')), true, 512, JSON_THROW_ON_ERROR);
return collect(data_get($composer, 'autoload.psr-4'))->reduce(function (Collection $carry, string $path, string $namespace) {
return collect(File::allFiles(base_path($path)))
->map(function ($item) use ($namespace) {
$path = $item->getRelativePathName();
return sprintf('\%s%s',
$namespace,
str_replace('/', '\\', substr($path, 0, strrpos($path, '.'))));
})
->filter(function ($class) {
if (!class_exists($class)) {
return false;
}
$reflection = new ReflectionClass($class);
return $reflection->isSubclassOf(Model::class) && !$reflection->isAbstract();
})
->reduce(fn(Collection $collection, $value) => $collection->push($value), $carry);
}, collect());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment