How to get a all eloquent models in laravel?

by scotty_walker , in category: PHP CMS , a year ago

How to get a all eloquent models in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , a year 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.

Related Threads:

How to join 3 tables using laravel eloquent?
How to use substring with laravel eloquent?
How to prevent duplicates in laravel eloquent?
How to call a variable in models in laravel?
How to chain eloquent relation in route in laravel?
How to convert sql query to eloquent in laravel?