1

I have a variable which holds the model name like so

$fooTableName = 'foo_defs';
$fooModel = 'FooDefs';

Now I would like to insert in the DB using that model like so

$fooModel::insert([..foo..array...]);

Throws an error

"message": "Parse error: syntax error, unexpected '$fooModel' (T_VARIABLE), expecting identifier (T_STRING)",

Is it possible to do something like that? or will I be forced to use

DB::table('fooTableName')->insert([...foo...array...]);

If I do it in the latter way, the timestamps in the table are wrong. The created_at column is null and the updated_at has the value

EDIT 1

 $model =  CustomHelper::getNameSpace($this->tableNames[$i]);
 // $model => /var/www/html/erp/app/Models/sales/InvoiceDefs
 $model::insert($this->tableCollections[$this->tableNames[$i]]);

Most of them said that, it was namespace issue, so I have corrected it, but still it is throw error like

"message": "Class '/var/www/html/erp/app/Models/sales/InvoiceDefs' not found",

7
  • What you want to do is possible, but that syntax error is being caused my something else. You need to post more code. Commented Mar 22, 2019 at 3:06
  • Can you post the rest of your code ... you might actually have a syntax error .... Commented Mar 22, 2019 at 3:06
  • Can you elaborate on your requirement? Your attempt makes me think that you have a situation where you would want to store records in tables based on certain situation or rules. Commented Mar 22, 2019 at 5:34
  • @vivek_23 Yes, it is storing records in the database, but the tables are always dynamic. For ex: I have 10 forms, all 10 forms store functionality I am trying to hit in one endpoint rather than 10 different endpoints i.e., creating a common function to store data from any form Commented Mar 22, 2019 at 5:54
  • @newUserName02, there are no syntax error for sure. Commented Mar 22, 2019 at 5:54

5 Answers 5

1

What you are doing wrong is using model name as string, you need to refactor your code as like below :

$fooModel = 'App\Models\FooDefs';
Sign up to request clarification or add additional context in comments.

1 Comment

Yes that was it. Thanks for help.
1

I have a same situation before and i have created the function to do this

function convertVariableToModelName($modelName='',$nameSpace='')
        {
            //if the given name space iin array the implode to string with \\
            if (is_array($nameSpace))
            {
                $nameSpace =  implode('\\', $nameSpace);
            }
            //by default laravel ships with name space App so while is $nameSpace is not passed considering the
            // model namespace as App
            if (empty($nameSpace) || is_null($nameSpace) || $nameSpace === "") 
            {                
               $modelNameWithNameSpace = "App".'\\'.$modelName;
            }
            //if you are using custom name space such as App\Models\Base\Country.php
            //$namespce must be ['App','Models','Base']
            if (is_array($nameSpace)) 
            {
                $modelNameWithNameSpace = $nameSpace.'\\'.$modelName;

            }
            //if you are passing Such as App in name space
            elseif (!is_array($nameSpace) && !empty($nameSpace) && !is_null($nameSpace) && $nameSpace !== "") 
            {
                $modelNameWithNameSpace = $nameSpace.'\\'.$modelName;

            }
            //if the class exist with current namespace convert to container instance.
            if (class_exists($modelNameWithNameSpace)) 
            {
                    // $currentModelWithNameSpace = Container::getInstance()->make($modelNameWithNameSpace);
                    // use Illuminate\Container\Container;
                    $currentModelWithNameSpace = app($modelNameWithNameSpace);
            }
            //else throw the class not found exception
            else
            {
                throw new \Exception("Unable to find Model : $modelName With NameSpace $nameSpace", E_USER_ERROR);
            }

            return $currentModelWithNameSpace;
        }

How To user it:

Arguments

First Argument => Name of the Model

Second Argument => Namespcce of the Model

For Example we have the model name as Post

$postModel = convertVariableToModelName('Post');

dd($postModel::all());

Will returns all the values in the posts table

But in Some Situation You Model Will in the

Custom Namespace such as App\Models\Admin\User

So this function is created to overcome that

$userModel = convertVariableToModelName('User',['App','Models','Admin']);

dd($userModel::all());

You are feel free to customize the function

Hope it helps

3 Comments

Thanks for the help. Your solutions gave me a start point. The issue was simple, there were no namespace.
no problem. But in Some Situation i have moved my models to the custom namespace Because Somebody prefers to keep it in App\Models Folder. i have created to overcome that.If you think my answer is good then marks is as accepted
and i also hate being writing the code again and again. So i have created the function to overcome that
1

Try the below one,

$fooModel = new FooDefs();

and then you can do the following also,

$fooModel->column1 = $value1;
$fooModel->column2 = $value2;
$fooModel->column2 = $value2;
$fooModel->save();

or

$fooModel->save([
    'column1' => $value1,
    'column2' => $value2,
    'column3' => $value3,    
])

Edited answer

$path = 'my\project\path\to\Models';
$fooModel = app($path.'\FooDefs');
$fooModel::save([
    'column1' => $value1,
    'column2' => $value2,
    'column3' => $value3,    
])
dd($fooModel ::all());

Try my edited answer.

1 Comment

the thing is that the Model names are dynamic, so I can explicitly says new FooDefs(), the model name is stored in a variable $fooModel;
0

When you have the name of class stored as string you can call method on that class by using the php method call_user_func_array like this

$class_name = "FooDefs";
call_user_func_array(array($class_name, "insert"), $data);

$data is an Array of data which will be past to the called function as arguments.

Just for simple advice It's will be Good if you save in the $class_name variable the FQN Fully Qualified Name of the class which is the __NAMESPACE__ follow by the name of the class. For sample purpose FQN look like Illuminate\Support\Facades\DB which you can get when you save you use User::class I presume you have some User model. That will return the Fully Qualified Name of the User model will will be App\User in case of Laravel.

Comments

0
 $requests = $post['request']     // posting the data from view page
 $models =  "app\models".'\\'.$requests  //geting the model 
 $model = $models::findOne($referenceId) //fetching value from database

1 Comment

Hello Anisha, welcome to SO. Perhaps you should elaborate your answer and how is it helping OP's question.

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.