Skip to content
Advertisement

Laravel getModelByTableName() function work locally but doesn’t work on the server

I have the following function written in phpLaravel

public static function getModelByTablename($tableName) {
    $model = new ('AppModels\'.Str::studly(strtolower(Str::singular($tableName))));
    return $model;
}

image

it works fine on my computer(windows 10) but on the server it doesn’t work and give me the following error

syntax error, unexpected ‘(‘

Advertisement

Answer

My approach would be this: (not tested)

public static function getModelByTablename($tableName) {
    $model = "AppModels\" . str($tableName)->singular()->studly();
    return new $model();
}

(str function is only available on laravel 9, otherwise use Str::of with the correct import)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement