How to get a all eloquent models in laravel?

by scotty_walker , in category: PHP CMS , 25 days ago

How to get a all eloquent models in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 22 days ago

@scotty_walker 

To get all eloquent models in Laravel, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
$models = collect(File::files(app_path()))
        ->map(function($item) {
            return str_replace('.php', '', basename($item));
        })
        ->filter(function($item) {
            $namespace = 'App\';
            $class = "{$namespace}{$item}";

            $reflect = new ReflectionClass($class);

            if ($reflect->isAbstract()) {
                return false;
            }

            return !$reflect->isInterface() && !$reflect->isTrait();
        })
        ->toArray();


This code will retrieve all the PHP files in the app directory and filter out any models that are abstract, interfaces, or traits. The result will be an array containing the names of all eloquent models in your Laravel application.