2

i have this CSV(without row headers)

001001,BENITEZ LI,2052,2059,2016-04-27 09:07:20
001002,CASA PARRO,13937,13945,2016-04-21 09:07:20
001004,NUEVO BANC,701,709,2016-04-23 22:07:20

Using this script:

Excel::filter('chunk')->load(public_path().'/uploads/'.$filename)->chunk(250, function($results) {
                    foreach ($results as $row) {
                        $user = Lectura::create([
                            'partida' => $row->partida,
                            'nombre' => $row->nombre,
                            'lectura_ant' => $row->lectura_ant,
                            'lectura_act' => $row->lectura_act,
                            'fecha' => $row->fecha,                                       
                        ]);
                    }
                });

I want import to my DB using this code, i can get correctly each line. But added null values. Dumping variable:

CellCollection {#734 ▼
  #title: null
  #items: array:5 [▼
    "001001" => "001002"
    "benitez_li" => "CASA PARRO"
    2052 => 13937.0
    2059 => 13945.0
    "2016_04_27_090720" => "2016-04-21 09:07:20"
  ]
}

Perhaps should be (how can define column names?):

CellCollection {#734 ▼
  #title: null
  #items: array:5 [▼
    "partida" => "001002"
    "nombre" => "CASA PARRO"
    "lectura_ant"=> 13937.0
    "lectura_act"=> 13945.0
    "fecha" => "2016-04-21 09:07:20"
  ]
}

or better (convert to array). How can get values? $row[1], $row[2]....

CellCollection {#734 ▼
  #title: null
  #items: array:5 [▼
    "0" => "001002"
    "1" => "CASA PARRO"
    "2"=> 13937.0
    "3"=> 13945.0
    "4" => "2016-04-21 09:07:20"
  ]
}
2
  • Did you set the $fillable variable in your Model? For Mass assignment you have to set it. protected $fillable = [ 'partida', 'nombre', 'lectura_ant', 'lectura_act', 'fecha' ]; Commented Mar 7, 2017 at 7:26
  • Thanks Andy. Yes, all filliable. I solved adding two lines $reader->toArray(); $reader->noHeading(); Commented Mar 7, 2017 at 12:26

1 Answer 1

1

Solved !! Adding two lines:

        $rows = Excel::load(public_path().'/uploads/'.$filename, function($reader) {
            $reader->toArray();
            $reader->noHeading();
        })->get();

       foreach ($rows as $row) {
           $item = array([
                'partida' => $row[0],
                'nombre' => $row[1],
                'lectura_ant' => $row[2],
                'lectura_act' => $row[3],
                'fecha' => $row[4], 
            ]);
            DB::table('lecturas_temp')->insert($item );
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Your are great! @Alejandro

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.