ItSolutionStuff.com

How to Get All Models in Laravel?

By Hardik Savani • April 16, 2024
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Create Model in Laravel using Command?

Read Now →

Laravel Ajax PUT Request Example Tutorial

Read Now →

Laravel Ajax GET Request Example Tutorial

Read Now →

Laravel Cookies - Get, Set, Delete Cookie Example

Read Now →

How to Store Array in Database Laravel?

Read Now →

How to Use Enum in Laravel?

Read Now →

FCM Push Notification in Laravel Example

Read Now →

Laravel Country State City Dropdown using Ajax Example

Read Now →

Laravel Ajax CRUD with Popup Modal Example

Read Now →

How to install and use Image Intervention in Laravel?

Read Now →

Laravel 9 Scout Full Text Search Tutorial

Read Now →