Skip to content

Instantly share code, notes, and snippets.

@mahammad
Created September 2, 2023 11:33
Show Gist options
  • Save mahammad/d15aa6aa80b646024921e16fcdd5d7c5 to your computer and use it in GitHub Desktop.
Save mahammad/d15aa6aa80b646024921e16fcdd5d7c5 to your computer and use it in GitHub Desktop.
How to get Model class by table name in Laravel
<?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