Hello Geek, Today I’ll show you how to get all models into Laravel. Let me show you the Laravel list of all models. You will learn how to get a list of all Laravel models.
In Laravel, a model is a PHP class that represents a database table. You can use models to retrieve, insert, and update data in the database.
In fact, this example works with Laravel 6, Laravel 7, Laravel 8, and Laravel 9.
Moreover, sometimes we need to get a list of all the eloquent models that have been created and want to print it out or use it in another way. For the same reason, while there is no method to get a list of all models in Laravel, we do know that all models are stored in the “Models” directory. Using a simple example, I’ll show you how to get all models into a Laravel application.
Let’s see a simple example with output:
<?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"
]
All the best, nerd!