How to Get All Models in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Create Model in Laravel using Command?
- Laravel Ajax PUT Request Example Tutorial
- Laravel Ajax GET Request Example Tutorial
- Laravel Cookies - Get, Set, Delete Cookie Example
- How to Store Array in Database Laravel?
- How to Use Enum in Laravel?
- FCM Push Notification in Laravel Example
- Laravel Country State City Dropdown using Ajax Example
- Laravel Ajax CRUD with Popup Modal Example
- How to install and use Image Intervention in Laravel?
- Laravel 9 Scout Full Text Search Tutorial