2

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
4
  • $model = new $modelName(); forgot to instantiate it Commented Jun 22, 2016 at 0:47
  • @Ohgodwhy Thanks for catching that. I updated the question, but the error didn't change. Commented Jun 22, 2016 at 0:50
  • how about $modelName = model::class? Commented Jun 22, 2016 at 0:50
  • @Burak good idea, but looks like the error remains :/ Commented Jun 22, 2016 at 0:52

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! that worked. I guess including the class path always has to be explicit in this case even when the class has been included?
also, why is it a backslash here instead of a foward slash?
I've edited my answer to include the link to related part of the PHP documentation. 1) Yes, it seems so. 2) It is the one used by PHP, right? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.