L
L
larik laravue2021-07-29 19:17:57
Laravel
larik laravue, 2021-07-29 19:17:57

How to fill model fields using key=>val array before save?

there is such a task - to replace the regular function

update(
[
$key1 =>$val1,
$key2 = $val2
]);


On your own, which would also accept these parameters, but inside so that there is a code

$newModel = new ModelName;
foreach ( $data as $key=>$val) {
   $newModel-> $key = $val;     // вместо этой строчки нужно вставить правильную конструкцию. но как?
}
$newModel->save();


As I understand it, Setter needs to be done on all fields of the model, but is there another way to implement setters without additional. coding?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Bedoyar, 2021-07-30
@laravue

The Model class has methods for filling model properties with values ​​from an array
- fill - subject to guard / fillable restrictions
- forceFill - without these restrictions
After filling, you need to save.
https://laravel.com/api/8.x/Illuminate/Database/El...
Link to documentation for version 8, but these methods seem to have been around for a long time. Check for your version of Lara.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question