In this article, I will show you how to get all models in laravel. We will implement a laravel get all models. You will learn laravel get all model list.
Laravel get all models , there are several methods you can approach it depending on how you have structured your application. Models are typically store in the app/Models directory.
Here are multiple example you can use to list or get all models dynamically in Laravel.
Read also: Laravel check database connection example
1. Laravel get all models using FIle::allFiles() method
If all your models are in the app/Models directory, you can use Laravel’s File class to the get all models.
Example:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
class IndexController extends Controller
{
public function getModel(Request $request) {
$modelPath = app_path('Models');
$models =[];
foreach(File::allFiles($modelPath) as $file) {
$models[] = 'App\Models\\'. $file->getFilenameWithoutExtension();
}
dd($models);
}
}
Explanation:
- app_path(‘Models’) fetches the path of the models folder.
- File::allFiles() scan the folder for all files.
- The loop adds each model to an array.
We need to get all list of created eloquent models and you want to print it out or whatever use it. Laravel does not provides any method to get all models list, but we know laravel store all models in “Models” directory. I will give you easy example of get all models in the laravel application.
Example: Get all models in Laravel
public function index(Request $request)
{
$allModels = $this->getModelsList();
dd($allModels);
}
public function getModelsList()
{
$path = app_path(). "/Models";
$models = [];
$results = scandir($path);
foreach($results as $result)
{
if($result === '.' or $result === '..') continue;
$filename = $path. '/' . $result;
if(is_dir($filename)) {
$models = array_merge($models, $path);
}else {
$models[] = substr($filename, 0, -4);
}
}
return $models;
}
This will give you a list of all models located in the app/Models directory. You can extend this functionality if your models are located in other directories as well.
I hope this tutorial help you.