Skip to content

Instantly share code, notes, and snippets.

@osamaAbdullah
Created July 17, 2020 23:25
Show Gist options
  • Save osamaAbdullah/8b1d87e53088acc6942874851b1d96bf to your computer and use it in GitHub Desktop.
Save osamaAbdullah/8b1d87e53088acc6942874851b1d96bf to your computer and use it in GitHub Desktop.
reading csv file and inserting it in the database
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