Created
September 2, 2023 11:33
-
-
Save mahammad/d15aa6aa80b646024921e16fcdd5d7c5 to your computer and use it in GitHub Desktop.
How to get Model class by table name in Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!function_exists('get_model_by_table')) { | |
function get_model_by_table($table): \Illuminate\Support\Collection | |
{ | |
$models = collect(); | |
if (\Illuminate\Support\Facades\File::isDirectory(app_path('Models'))) { | |
$model_files = array_filter(\Illuminate\Support\Facades\File::allFiles(app_path('Models')), function ($file) { | |
return $file->getExtension() === 'php'; | |
}); | |
foreach ($model_files as $model_file) { | |
$model_class = str($model_file->getRealPath())->replace([base_path(), '/app', '.php', '/'], ['', 'App', '', '\\'])->toString(); | |
if ((app($model_class)->getTable() ?? null) == $table) | |
$models->push([ | |
'class' => $model_class, | |
'table' => $table, | |
]); | |
} | |
} | |
return $models; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment