How to Get All Models in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hi,

Here, I will show you how to get all models in laravel. In this article, we will implement a laravel get list of all models. I would like to show you laravel list all models. you will learn laravel get all model list.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Sometimes, we need to get all list of created eloquent models and you want to print it out or whatever use it. So, laravel does not provides any method to get all models list, but we know laravel store all models in "Models" directory. so i will give you a simple example of how to get all models in the laravel application.

let's see a simple example with output:

Example:

You can see below controller file code.

Controller File Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$allModels = $this->getAllModels();

dd($allModels);

}

/**

* Write code on Method

*

* @return response()

*/

public function getAllModels()

{

$modelList = [];

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

$results = scandir($path);

foreach ($results as $result) {

if ($result === '.' or $result === '..') continue;

$filename = $result;

if (is_dir($filename)) {

$modelList = array_merge($modelList, getModels($filename));

}else{

$modelList[] = substr($filename,0,-4);

}

}

return $modelList;

}

}

Output:

^ array:9 [â–¼

0 => "City"

1 => "Contact"

2 => "Country"

3 => "Item"

4 => "Post"

5 => "Product"

6 => "State"

7 => "User"

8 => "Visitor"

]

I hope it can help you...

Tags :
Shares