首页 > 解决方案 > 试图在 Laravel 中发布一个对象数组。ErrorException:从文件中的空值创建默认对象

问题描述

我正在尝试使用这样的数据集发送 POST 请求:

[
    {
    "Course_Code":"CIS341",
    "Start_Date":"2020-08-22",
    "End_Date":"2020-12-02",
    "CRN":345627,
    "CWID":"C38475920",
    "Date_Registered":"2020-04-02"
    },
    {
    "Course_Code":"CIS341",
    "Start_Date":"2020-08-22",
    "End_Date":"2020-12-02",
    "CRN":456392,
    "CWID":"C38475920",
    "Date_Registered":"2020-04-02"
    },
    {
    "Course_Code":"CIS341",
    "Start_Date":"2020-08-22",
    "End_Date":"2020-12-02",
    "CRN":562940,
    "CWID":"C38475920",
    "Date_Registered":"2020-04-02"
    }
]

但我只想将每个对象的 CRN、CWID、Date_Registered 插入到我的 final_schedule 表中:

protected $table ="final_schedule";
  public $timestamps = false;
  protected $fillable = [
    'CWID',
    'CRN',
    'Date_Registered'
  ];

这是我正在使用的插入功能:

public function insert(Request $request){
      $CWID->CWID = $request->input('CWID');
      $CRN->CRN = $request->input('CRN');
      $Date_Registered->Date_Registered = $request->input('Date_Registered');

      $items = array('CWID'=>$CWID, 'CRN'=>$CRN, 'Date_Registered'=>$Date_Registered);
      finalScheduleModel::insert($items);
    }

当我在邮递员中测试这个插入函数时,它给出了错误: ErrorException: Creating default object from empty value in file 错误指向的行是函数的第一行 $CWID->CWID = $request->input('CWID'); 我尝试以多种不同的方式编写这个函数,但我一直在同一行中遇到错误。它从不读取任何发送过来的数据。它可能会说试图将值 CWID、CRN、Date_Registered (?,?,?) 插入到 final_schedule 中。

标签: sqllaravelposteloquentinsert

解决方案


试试这个看看这是否适合你。

public function insert(Request $request){
          $array = [];
    foreach (request()->all() as $value) {
        array_push($array, ['CWID' => $value['CWID'], 'CRN' => $value['CRN'], 'Date_Registered' => $value['Date_Registered']]);
    }

    DB::table('final_schedule')->insert($array);
    }

推荐阅读