Created
July 17, 2020 23:25
-
-
Save osamaAbdullah/8b1d87e53088acc6942874851b1d96bf to your computer and use it in GitHub Desktop.
reading csv file and inserting it in the database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function importCsv($model, $fileName) | |
{ | |
$model = '\\App\\Models\\' . $model; | |
$file = public_path('csv/' . $fileName . '.csv'); | |
$arr = $this->csvToArray($file); | |
foreach ($arr as $row) | |
{ | |
unset($row['id']); | |
unset($row['created_at']); | |
unset($row['updated_at']); | |
$model::create($row); | |
} | |
return 'All data imported successfully.'; | |
} | |
private function csvToArray($filename = '', $delimiter = ',') | |
{ | |
if (!file_exists($filename) || !is_readable($filename)) { | |
return false; | |
} | |
$columns = null; | |
$data = []; | |
if (($file = fopen($filename, 'r')) !== false) | |
{ | |
while (($row = fgetcsv($file, 5000, $delimiter)) !== false) | |
{ | |
if (!$columns) { | |
$columns = $row; | |
} | |
else { | |
$data[] = array_combine($columns, $row); | |
} | |
} | |
fclose($file); | |
} | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment