Foreach插入Laravel 5 Eloquent

问题描述:

Trying to insert records using a foreach loop.

$test = array(123, 231, 321, 543);

foreach($test as $key) {
    $data = array('name' => 'test_name', test' => $test[$key], 'property' => 'test_property');
    Test_table::insert($data);    
}

Using a foreach gives an error Undefined offset: 123.

Inserting this way works though:

 $data = array(
    array('name' => 'test_name', test' => 123, 'property' => 'test_property'), 
    array('name' => 'test_name', test' => 231, 'property' => 'test_property'), 
    array('name' => 'test_name', test' => 321, 'property' => 'test_property'), 
    array('name' => 'test_name', test' => 543, 'property' => 'test_property'),
  );
 Test_table::insert($data);  

What is wrong?

$test = array(123, 231, 321, 543);
foreach($test as $key) {
    $data = array('name' => 'test_name', 'test' => $key, 'property' => 'test_property');
    Test_table::insert($data);    
}

This should work. You don't need to access $test by index since you already have the value in $key which is in fact a value from the array.

try following Code :

$test = array(123, 231, 321, 543);
foreach($test as $key) {

$createtesttable=Test_table::create(['name' => 'test_name', 'test' => $key, 'property' => 'test_property']);

}