Using Model name from Variable

laravel model variable
laravel get model name
laravel model custom variable
laravel model fields
laravel model attributes
laravel model relationships
select with model in laravel
how to use mutators in laravel

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",

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

$fooModel = 'App\Models\FooDefs';

Variable as model name, is it possible?, Hi Is there a way we can specify the name of a model by a variable? you should use different models to address these specific tables. The model loads data to the MATLAB base workspace. Open Model Explorer. In the Model Hierarchy pane, select the base workspace. In the Contents pane, right-click the base workspace variable m and select Rename All. In the Select a system dialog box, click the name of the model sldemo_absbrake to select it as the context for renaming the variable m.

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

Retrieving Models with Name in a Variable. ex $class::all(), It's getting the value fine and use of: $recipes = Recipe::all();. Works fine elsewhere in the controller. When using a variable, say $class, containing ' Recipe' and� MDT has a script called ztigather.wsf that runs and gathers both the Make and Model of machines already so instead of using a WMI query just use a condition with a Task Sequence variable called Model. The challenge is when trying to do this with Lenovo systems. Lenovo systems do not properly set the Model to what you would think it would be.

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.

Model.getVarByName(), Model.getVarByName() Variables and Constraints and Objectives. Variables. Constraints. Objectives Variable with the specified name. Example usage: Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Jobs Programming and related technical career opportunities

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.

How can I programmatically call "exampleModel(,'compile')" using , Learn more about programatically, compile, multiple, models Simulink. call " exampleModel(,'compile')" using a variable for my model name? When I ran the model, it selected each - in this case building - number and showed it in the existing feature layer. Only problem is it wouldn't create a new feature layer in the table of contents for some reason. It had no problem using the variable in the new layer name, just wouldn't display the new layer.

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

Using variables, Variables can be used to configure timezones, avoid hardcoding table names or otherwise To use a variable in a model, hook, or macro, use the {{ var('. And since the Name parameter takes a string, it’s quite easy to create a dynamic name using a loop on our prefixes array, and by using an expression in the string to dynamically build our variable name. Notice that I’m using the Force switch to make sure that the variables will be created even if a variable with the same name exists already.

Working with variables, In the context of a model, a variable can be created and its value used as a tool's variable using the tool dialog, since the parameter control shows the name of� One Mona Lisa, etc. Figure out where to define a variable, and don’t make it complicated. However, let’s go ahead and get precedence out of the way! It exists. It’s a real thing, and you might have a use for it. If multiple variables of the same name are defined in different places, they get overwritten in a certain order.

How to save model name with my own variable? � Issue #229 , comments claim that """Save the model after every epoch. filepath can contain named formatting options, which will be filled the value of epoch� For example, use this syntax to determine where a variable is used in a model. example [ variables ] = Simulink.findVars( ___ , Name,Value ) finds variables with additional options specified by one or more Name,Value pair arguments.

Model associations seems to use the model name and not the , seems to use the model name and not the protected $table variable. I have one Model call _Request (because Request is a reserved word

Comments
  • What you want to do is possible, but that syntax error is being caused my something else. You need to post more code.
  • Can you post the rest of your code ... you might actually have a syntax error ....
  • 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.
  • @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
  • @newUserName02, there are no syntax error for sure.
  • Yes that was it. Thanks for help.
  • 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
  • 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;
  • Hello Anisha, welcome to SO. Perhaps you should elaborate your answer and how is it helping OP's question.