how to update data in database with import excel. i am using laravel 5.7 and maatwebsite 3.1
this is my controller :
public function import()
{
$data = Excel::toArray(new ProdukImport, request()->file('file'));
if ($data) {
DB::table('produk')
->where('id_produk', $data['id'])
->update($data);
}
}
This is my Import Class:
<?php
namespace App\Imports;
use App\Produk;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProdukImport implements ToModel, WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Produk([
'id_produk' => $row['id'],
'nama_produk' => $row['produk'],
'harga_jual' => $row['harga']
]);
}
}
this dd($data) result :
array:1 [▼
0 => array:8 [▼
0 => array:3 [▼
"id" => 1.0
"produk" => "Pomade"
"harga" => 90000.0
]
1 => array:3 [▼
"id" => 2.0
"produk" => "Shampoo"
"harga" => 90000.0
]
2 => array:3 [▼
"id" => 3.0
"produk" => "Sikat WC"
"harga" => 90000.0
]
]
]
the $data
result is from this :
$data = Excel::toArray(new ProdukImport, request()->file('file'));
Based on the structure of your $data
array, you could probably achieve what you want with something like this:
public function import()
{
$data = Excel::toArray(new ProdukImport, request()->file('file'));
return collect(head($data))
->each(function ($row, $key) {
DB::table('produk')
->where('id_produk', $row['id'])
->update(array_except($row, ['id']));
});
}