Skip to content

Instantly share code, notes, and snippets.

@muath-ye
Created September 24, 2023 07:56
Show Gist options
  • Save muath-ye/889ec9e738fb05d34a0e92a90169526b to your computer and use it in GitHub Desktop.
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()
// 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