Created
September 24, 2023 07:56
-
-
Save muath-ye/889ec9e738fb05d34a0e92a90169526b to your computer and use it in GitHub Desktop.
A Laravel help to access your models as functions like user()->first()
This file contains 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
// Get all files from the App\Models directory | |
$modelFiles = glob(app_path('Models/*.php')); | |
foreach ($modelFiles as $modelFile) { | |
// Extract the filename without the .php extension for the function name | |
$modelName = strtolower(basename($modelFile, '.php')); | |
// Create the full class name | |
$fullClassName = "\\App\\Models\\" . ucfirst($modelName); | |
// Check if class exists and it's not abstract | |
if (class_exists($fullClassName)) { | |
$reflection = new ReflectionClass($fullClassName); | |
if (!$reflection->isAbstract()) { | |
// Define the function | |
if (! function_exists($modelName)) { | |
$functionDefinition = "function $modelName() { return app('$fullClassName'); }"; | |
eval($functionDefinition); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment