Skip to content
Advertisement

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.

Advertisement

Answer

I would navigate through your filesystem and pull out all of the php files from your models folder. I keep my models in the app/Models folder so something like this:

$path = app_path() . "/Models";

function getModels($path){
    $out = [];
    $results = scandir($path);
    foreach ($results as $result) {
        if ($result === '.' or $result === '..') continue;
        $filename = $path . '/' . $result;
        if (is_dir($filename)) {
            $out = array_merge($out, getModels($filename));
        }else{
            $out[] = substr($filename,0,-4);
        }
    }
    return $out;
}

dd(getModels($path));

I just tried this and it spit out the full filepath of all of my models. You could strip the strings to make it only show the namespace and model name if thats what you are looking for.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement