Skeets O'Reilly Skeets O'Reilly - 1 year ago 188
PHP Question

(laravel) Query builder using model of variable name

I'm trying to insert into a table using its laravel model class, but I need to be able to insert into the table indicated by a variable. How can this be done? I tried the vanilla PHP moethod and the laravel facade method but both gave me errors:

$modelName = "model";

# this works no problem:
$model = new model();

# this blows up:
$model = new $modelName();

# this blows up:

the error given by laravel:

FatalThrowableError in Controller.php line 44:
Class 'model' not found

Answer Source

You must put the fully qualified class name:

One must use the fully qualified name (class name with namespace prefix).

$modelName = "App\\User"; // assuming User is located in the App namespace
$model = new $modelName();

You can learn more about it here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download