1

I want to record equipment in many forms, but errors always occur. Undefined index: name

public function EquipCheck(Request $request) {
    $user = User::where('username', $request -> username) -> firstOrFail();
    if ($request -> token == $user -> token) {
        $item_detail_id = CheckLog::where('user_id', $user -> id) -> orderBy('id', 'desc') -> first() -> item_detail_id;
        $new_form = new Form;
        $new_form -> item_detail_id = $item_detail_id;
        $new_form -> user_id = User::where('username', $request -> username) -> firstOrFail() -> id;
        $new_form -> created_time = Carbon::now() -> format('Y-m-d H:i:s');
        $new_form -> save();
        $form = Form::with('eqpt') -> where('item_detail_id', $item_detail_id) -> orderBy('created_time', 'desc') -> first();

        $data = $request -> eqpt;
        $i = 0;
        $sql = array();

        while($i < count($cyldata['serie'])){
            $sql[] = array(
                'form_id' => $form -> id,
                'name' => $data['name'][$i],
                'unit' => $data['unit'][$i],
                'quantity' => $data['quantity'][$i],
                'check_quantity' => $data['check_quantity'][$i],
            );
            $i++;
        }

        DB::table('eqpt') -> insert($sql);

        return "Success";
    }
}

When I use the following code, the database can be inserted the array.

$dataSet[] = [
            'form_id' => $form -> id,
            'name' => 'test',
            'unit' => 'box',
            'quantity' => 20,
            'check_quantity' => 20,
        ];

        DB::table('eqpt') -> insert($dataSet);

This is post data.

  • Have you tried inspecting the `$data` variable after you set it? Also, where is `$cyldata['serie']` being set? – jackel414 May 05 '17 at 18:22
  • How can I recreate array from the post data? –  May 06 '17 at 01:38
  • have you created dd($data)? can you let us know the result? – Peyman May 06 '17 at 03:09
  • It might be an issue of character set collation, have you tried changing the character set and collation? This link might help you http://stackoverflow.com/questions/14456313/cant-insert-chinese-character-into-mysql – linktoahref May 06 '17 at 13:51

1 Answers1

2

$data contains an array of objects. $data['name'] refers to the property of that array, while you should access properties of objects in that array.

Replace

$sql[] = array(
  'form_id' => $form -> id,
  'name' => $data['name'][$i],
  'unit' => $data['unit'][$i],
  'quantity' => $data['quantity'][$i],
  'check_quantity' => $data['check_quantity'][$i],
);

with

$sql[] = array(
  'form_id' => $form -> id,
  'name' => $data[$i]['name'],
  'unit' => $data[$i]['unit'],
  'quantity' => $data[$i]['quantity'],
  'check_quantity' => $data[$i]['check_quantity'],
);
jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107