Skeets O'Reilly Skeets O'Reilly - 5 months ago 61
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:
$model::create($request->all());


the error given by laravel:

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

Answer

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.