Advertisement
chiflon

Laravel 4 seeding from csv file

Oct 6th, 2013
2,092
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.29 KB | None | 0 0
  1. <?php
  2.  
  3. class AreasTableSeeder extends Seeder {
  4.  
  5.     public function run()
  6.     {
  7.         // Uncomment the below to wipe the table clean before populating
  8.         // DB::table('areas')->delete();
  9.  
  10.         function csv_to_array($filename='', $delimiter=',')
  11.             {
  12.                 if(!file_exists($filename) || !is_readable($filename))
  13.                     return FALSE;
  14.              
  15.                 $header = NULL;
  16.                 $data = array();
  17.                 if (($handle = fopen($filename, 'r')) !== FALSE)
  18.                 {
  19.                     while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
  20.                     {
  21.                         if(!$header)
  22.                             $header = $row;
  23.                         else
  24.                             $data[] = array_combine($header, $row);
  25.                     }
  26.                     fclose($handle);
  27.                 }
  28.                 return $data;
  29.             }
  30.  
  31.             /****************************************
  32.             * CSV FILE SAMPLE *
  33.             ****************************************/
  34.             // id,subdireccion_id,idInterno,area,deleted_at,created_at,updated_at
  35.             // ,1,4,AREA MALAGA OCC.,,2013/10/13 10:27:52,2013/10/13 10:27:52
  36.             // ,1,2,AREA MALAGA N/ORIENT,,2013/10/13 10:27:52,2013/10/13 10:27:52
  37.              
  38.             $csvFile = public_path().'/tabla_areas.csv';
  39.  
  40.             $areas = csv_to_array($csvFile);
  41.  
  42.  
  43.         // Uncomment the below to run the seeder
  44.         DB::table('areas')->insert($areas);
  45.     }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement