55 lines
1.7 KiB
PHP
55 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Http\Request;
|
|
use Maatwebsite\Excel\Facades\Excel;
|
|
use Illuminate\Support\Facades\File;
|
|
use App\Imports\ImportData;
|
|
use App\Models\DataDBD;
|
|
use App\Models\Kecamatan;
|
|
|
|
class DataController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$dataDBD = DataDBD::with('kecamatan')->get();
|
|
|
|
return view('data', compact('dataDBD'));
|
|
}
|
|
|
|
public function import(Request $request)
|
|
{
|
|
// Validasi file yang diunggah
|
|
$request->validate([
|
|
'file' => 'required|file|mimes:xlsx,xls',
|
|
]);
|
|
|
|
// Ambil data kecamatan beserta ID-nya
|
|
$kecamatans = Kecamatan::all()->pluck('id', 'nama_kecamatan');
|
|
|
|
// Ambil data dari file yang diunggah
|
|
$importedData = Excel::toArray(new ImportData, $request->file('file'));
|
|
|
|
// Loop melalui data yang diimpor
|
|
foreach ($importedData[0] as $data) {
|
|
// Cocokkan nama kecamatan dari file Excel dengan daftar nama kecamatan
|
|
if (isset($kecamatans[$data['kecamatan']])) {
|
|
$id_kecamatan = $kecamatans[$data['kecamatan']];
|
|
|
|
// Simpan data dengan ID kecamatan yang cocok
|
|
DataDBD::create([
|
|
'id_kecamatan' => $id_kecamatan,
|
|
'tahun' => $data['tahun'],
|
|
'bulan' => $data['bulan'],
|
|
'jumlah_kasus' => $data['jumlah_kasus']
|
|
]);
|
|
} else {
|
|
// Kecamatan tidak ditemukan, lakukan penanganan yang sesuai
|
|
}
|
|
}
|
|
|
|
return redirect()->back()->with('success', 'File Excel berhasil diunggah dan data berhasil diimpor.');
|
|
}
|
|
}
|