I would like to find a list of all models, database tables as a backup, in a Laravel project.
I want to do this to build a dashboard that displays the way data in all of the models has changed over time, I.E. if there is a user model, how many users have been added or modified each day for the last 90 days.
The built in User model is placed directory under app/ . If you want to use a specific folder for all your models, create on inside app/ named Models and then namespace all your models with App\Models\X .
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection.
I would like to suggest a different approach by using PHP reflection instead of relying that all models will reside in a namespace or directory called Model.
The code sample below collects all the application classes, verifies if they actually extend the Eloquent Model class and are not abstract.
<?php
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;
function getModels(): Collection
{
$models = collect(File::allFiles(app_path()))
->map(function ($item) {
$path = $item->getRelativePathName();
$class = sprintf('\%s%s',
Container::getInstance()->getNamespace(),
strtr(substr($path, 0, strrpos($path, '.')), '/', '\\'));
return $class;
})
->filter(function ($class) {
$valid = false;
if (class_exists($class)) {
$reflection = new \ReflectionClass($class);
$valid = $reflection->isSubclassOf(Model::class) &&
!$reflection->isAbstract();
}
return $valid;
});
return $models->values();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With