Last active
March 19, 2023 05:41
-
-
Save albofish/44e90efa9ec1ce7cab35 to your computer and use it in GitHub Desktop.
Laravel CSV to Array
This file contains hidden or 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
<?php | |
// ini_set("auto_detect_line_endings", true); // If having issues on iOS | |
trait CSVSeeder { | |
public function csv_to_array($filename = '', $delimiter = ',') { | |
if (!file_exists($filename) || !is_readable($filename)) | |
return FALSE; | |
$header = NULL; | |
$data = array(); | |
if (($handle = fopen($filename, 'r')) !== FALSE) { | |
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { | |
if (!$header) | |
$header = $row; | |
else | |
$data[] = array_combine($header, $row); | |
} | |
fclose($handle); | |
} | |
return $data; | |
} | |
} |
This file contains hidden or 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
<?php | |
class [Model]TableSeeder extends Seeder { | |
use CSVSeeder; | |
public function run() { | |
$csvFile = public_path() . '/[Model]-seeder.csv'; | |
$data = $this->csv_to_array($csvFile); | |
DB::table('[Model]')->truncate(); | |
DB::table('[Model]')->insert($data); | |
// or | |
//foreach($data as $entry) | |
//{ | |
// [Model]::create($data); | |
//} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment