I have this code to import to database some excel file. It takes too much time, more than 30 seconds, so php sends me an error due max time limit. I don't want to disable that time, nor put more time on php (set_timeout(0)
). For 20 registries it takes les than 30 seconds but I need to do it with 1000 registries aprox:
public function importExcel(Request $request)
{
if($request->file('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get()->toArray();
if(!empty($data) && (count($data)> 0)){
$errorCaga = false;
$array_errores = [];
foreach ($data as $key => $value) {
$r_ex_bases = AdminResolucionExenta::where('nombre',$value["r._ex._bases"])->pluck( 'id_resolucion_exenta')->first();
$decreto_precio_nudo = AdminDecretoPrecioNudo::where('nombre',$value["dec._p._nudo"])->pluck( 'id_decreto_precio_nudo')->first();
$modalidad = AdminModalidade::where('nombre',$value["modalidad"])->pluck( 'id_modalidad')->first();
$licitacion = AdminLicitacione::where('nombre',$value["licitacion"])->pluck( 'id_licitacion')->first();
$tipo_bloque = AdminTipoBloque::where('nombre',$value["tipo_bloque"])->pluck( 'id_tipo_bloque')->first();
$bloque = AdminBloque::where('nombre',$value["bloque"])->pluck( 'id_bloque')->first();
$distribuidora = AdminDistribuidora::where('nombre',$value["distribuidora"])->pluck( 'id_distribuidora')->first();
$punto_oferta = AdminPuntoOferta::where('nombre',$value["punto_oferta"])->pluck( 'id_punto_oferta')->first();
$punto_compra = AdminPuntoCompra::where('nombre',$value["punto_compra"])->pluck( 'id_punto_compra')->first();
$generadora = AdminGeneradora::where('nombre',$value["generadora"])->pluck( 'id_generadora')->first();
if(is_null($r_ex_bases) || is_null($decreto_precio_nudo) || is_null($modalidad) || is_null($licitacion) || is_null($tipo_bloque) || is_null($bloque) || is_null($distribuidora) || is_null($punto_oferta) || is_null($punto_compra) || is_null($generadora)){
array_push($array_errores,$value);
$errorCaga = true;
}else{
$datos = new AdminContrato;
$datos->resolucion_exenta_id = $r_ex_bases;
$datos->decreto_precio_nudo_id = $decreto_precio_nudo;
$datos->modalidad_id = $modalidad;
$datos->licitacion_id = $licitacion;
$datos->tipo_bloque_id = $tipo_bloque;
$datos->bloque_id = $bloque;
$datos->distribuidora_id = $distribuidora;
$datos->punto_oferta_id = $punto_oferta;
$datos->punto_compra_id = $punto_compra;
$datos->generadora_id = $generadora;
$datos->save();
}
}
//some more code to return and exit.
How could I do this more efficient? I'm new to Laravel, I know that creating an object new AdminContrato
isn't the best way. Would the chunk()
method helps on this?