2

Eloquent offers a handy way of passing stuff to the database

$table_name = new TableName;
$table_name->column_name = "some data";
$table_name->save();

I've got quite a lot of data from a form that needs to be validated, so I was wondering if it was possible to replace the column name with a variable, so I can put it in some loop, and get the names and data from arrays.

$table_name->$columns[$i] = $data[$i];

(though I suppose not written in that way)

Update

In the end I've gone with the following:

$table_name = new TableName;
$nameArray=[
  1 => 'form-name-1',
  ...
];
$columnArray=[
  1 => 'column_name_1',
  ...
];

for($i=1;$i<=count($nameArray);$i++){
  if(logic logic logic) $table_name->{$columnArray[$i]} = $_POST[$nameArray[$i]];
  else $table_name->{$columnArray[$i]} = NULL;
}
$table_name->save();
1
  • If it's validation you need done then check Laravel Validation which may save you lots of ifs Commented Sep 15, 2017 at 9:52

2 Answers 2

5

You can do one these:

1) Create with values

   $table_name = new TableName([
       "column_name" => "column_value"
   ]);

2) Fill

$table_name = new TableName();
$table_name->fill([
    "column_name" => "column_value"
]);

3) The way you suggested originally:

$valuesMap = [
    "column_name" => "column_value"
];
$table_name = new TableName();
foreach ($valuesMap as $column => $value) {
       $table_name->{$column} = $value; //The {} are optional in this case
}

Note that to do 1 or 2 all fields you put in the array must be fillable and not guarded.

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

1 Comment

Thx! I've gone for a variation of the 3rd option, since I needed to add some more logic before setting the value (the logic was always the same, that's why i asked the question.
1

You can use it like an associative array:

$table_name['column_name'] 
$column_name = 'column_name';
$table_name[$column_name];

Or you can loop their attributes

    foreach($table_name->getAttributes() as $value => $key){
     echo "The attr ".$key." has this value: ".$value;
    }

Comments

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.