Home Laravel How to Get All Models in Laravel?

How to Get All Models in Laravel?

by Shahriar Sagor
Get All Models in Laravel

Today now in this post, I will teach you how to get all models in laravel. So in this article, i will implement laravel get list of all models. Here I would like to share with you laravel list all models. We will learn about laravel get all model list.

We can also use this example with laravel 6, laravel 7, laravel 8 and laravel 9 any versions.

Sometimes, we may need to get all list of created eloquent models and also we want to print it out or whatever use it. So, laravel does not provides any method to get the all models list. But we know that in laravel store all models in the “Models” directory. So easily i will give you a very simple example of how to get the all models in the laravel application.

Just start let’s see the simple example:

Example:

You can see this in the 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;
    }
}

Read Also: How to Get All Session Data in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like