Laravel表单仅提交分配给模型的选定数据

时间:2018-09-01 12:43:12

标签: php laravel

我该如何仅将选定的数据保存到数据库表中

// save weekdays
        $weekdays = new TrainingDay();
        $weekdays->insert($request->weekdays->toArray());
        $weekdays->save();

该表只有id, plan_id, weekday, created_at, updated_at,我应该使用一些array_pluck还是其他东西?


我的样品表格提交数据

  #attributes: array:5 [
    "id" => "1"
    "plan_id" => "1"
    "weekday" => "Trænings dag"
    "created_at" => "2018-08-29 17:42:30"
    "updated_at" => "2018-08-29 17:42:30"
  ]

2 个答案:

答案 0 :(得分:1)

尝试此代码

$weekdays = new TrainingDay();
$weekdays->insert($request->except(['created_at', 'updated_at']));
$weekdays->save();

答案 1 :(得分:1)

您也可以使用only方法。

$weekdays = new TrainingDay();
$weekdays->insert($request->only(['id', 'plan_id', 'weekday']));
$weekdays->save();