Skip to content

Instantly share code, notes, and snippets.

@mohammad425
Created August 25, 2020 18:07
Show Gist options
  • Save mohammad425/231242958edb640601108bdea7bcf9ac to your computer and use it in GitHub Desktop.
Save mohammad425/231242958edb640601108bdea7bcf9ac to your computer and use it in GitHub Desktop.
Get a list of all models in Laravel
<?php
use Illuminate\Support\Facades\File;
function getAllModels(): array
{
$composer = json_decode(file_get_contents(base_path('composer.json')), true);
$models = [];
foreach ((array)data_get($composer, 'autoload.psr-4') as $namespace => $path) {
$models = array_merge(collect(File::allFiles(base_path($path)))
->map(function ($item) use ($namespace) {
$path = $item->getRelativePathName();
return sprintf('\%s%s',
$namespace,
strtr(substr($path, 0, strrpos($path, '.')), '/', '\\'));
})
->filter(function ($class) {
$valid = false;
if (class_exists($class)) {
$reflection = new \ReflectionClass($class);
$valid = $reflection->isSubclassOf(\Illuminate\Database\Eloquent\Model::class) &&
!$reflection->isAbstract();
}
return $valid;
})
->values()
->toArray(), $models);
}
return $models;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment