Ad

Trying To Post An Array Of Objects In Laravel. ErrorException: Creating Default Object From Empty Value In File

- 1 answer

I'm trying to send a POST request with a data set like this:

[
    {
    "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"
    }
]

But I only want to insert the CRN, CWID, Date_Registered from each of those objects into my final_schedule table:

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

Here is the insert function I'm using:

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);
    }

When I test this insert function in postman it gives the error: ErrorException: Creating default object from empty value in file And the line the error is pointing to is the first line of the function $CWID->CWID = $request->input('CWID'); I tried writing this function many different ways, but I keep getting errors along the same lines. It never reads any of the data being sent over. It might say something like trying to insert values CWID, CRN, Date_Registered (?,?,?) into final_schedule.

Ad

Answer

Try this see if this works for you.

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);
    }
Ad
source: stackoverflow.com
Ad