i have function in my controller that uses php excel to read rows from excel file, and store it to db table.
public function processData(Request $request)
{
/* store data from form in to variables */
$hotel = $request->input('hotel');
$date = $request->input('date');
$start_row = $request->input('row');
$date_col = $request->input('date-col');
$sold_col = $request->input('sold-col');
$rev_col = $request->input('rev-col');
/* get tables name */
$table = str_replace('-', '_', $hotel);
$monthly_table = $table . '_monthly';
/* init hotel class */
$hotel_table = new Hotel($table);
$file = public_path().'/'.$date.'.xls';
$sheetData = Excel::load($file)->noHeading()->getExcel()->getSheet()->toArray(null,false,false, true);
$sheetData = array_slice($sheetData, $start_row - 1);
foreach ($sheetData as $row)
{
if ($this->isDate($row[$date_col]))
{
print $row[$date_col] . "---" . $row[$sold_col] . "---" . gettype(money_format('%i', floatval($row[$rev_col]))) . "<br>";
$hotel_table->date = $row[$date_col];
$hotel_table->sold = intval($row[$sold_col]);
$hotel_table->sold_diff = 0;
$hotel_table->rev = floatval($row[$rev_col]);
$hotel_table->rev_diff = 0;
$hotel_table->row = $start_row;
$hotel_table->date_col = $date_col;
$hotel_table->sold_col = $sold_col;
$hotel_table->rev_col = $rev_col;
//$hotel_table->save();
if (!$hotel_table->save())
{
dd ( DB::getQueryLog() );
}
}
}
}
public function isDate($date)
{
if (date('m/d/Y', strtotime($date)) == $date)
{
return true;
}
else
{
return false;
}
}
this is my table
Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('date');
$table->integer('sold');
$table->integer('sold_diff');
$table->float('rev');
$table->float('rev_diff');
$table->string('row');
$table->string('date_col');
$table->string('sold_col');
$table->string('rev_col');
$table->timestamps();
});
when i go thru the foreach its printing things just fine to the screen there are no errors, but when i look at the table it only has last element of the array in db table.
If Hotel
class is your model then you need to move following code inside foreach
block
foreach ($sheetData as $row)
{
if ($this->isDate($row[$date_col]))
{
$hotel_table = new Hotel($table);
...
}
}