Skeets
Skeets

Reputation: 4828

(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

Upvotes: 2

Views: 2963

Answers (1)

Doom5
Doom5

Reputation: 858

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.

Upvotes: 6

Related Questions