Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a list of all models in Laravel?

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.

like image 284
Tommy Nicholas Avatar asked Dec 02 '15 21:12

Tommy Nicholas


People also ask

Where are all the Laravel models stored at?

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 .

What is __ DIR __ In Laravel?

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.

Which of the following methods on collection will get all the records from it Laravel?

Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection.


1 Answers

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();
}
like image 127
RibeiroBreno Avatar answered Oct 11 '22 10:10

RibeiroBreno