Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.1K
Vistas
Laravel: Insert multiple records with auto fill created_at & updated_at

I am trying to save multiple records in DB and have an array which looks like:-

$insert_data = array(
array(record 1),
array(record 2),
array(record 3)
)

Now, I tried two options:-

  1. Model::create($insert_data) But it doesn't create any entry in DB.
  2. Model::insert($insert_data) It's creating entry in DB with null datestamps.

I wanna insert multiple records with valid timestamps.

TIA

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

create() is a function from Eloquent, insert() - Query Builder.

You probably do not use Eloquent when inserting data, in this case you should add timestamps manually.

If you do not want to do this, but you still need filled timestamps, use this trick:

$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

Or, you can add timestamp like this :

$now = Carbon::now('utc')->toDateTimeString();
$data = array(
    array(
        'name'=>'Coder 1', 
         'rep'=>'4096',
        'created_at'=> $now,
        'updated_at'=> $now
       ),
    array(
         'name'=>'Coder 2', 
         'rep'=>'2048',
         'created_at'=> $now,
         'updated_at'=> $now
       ),
    //...
);

Coder::insert($data);
over 4 years ago · Santiago Trujillo Denunciar

0

You can use the upsert method since Laravel 8.

Model::upsert(
    array(
        array(record 1),
        array(record 2),
        array(record 3)
    ),
    'id'
);
over 4 years ago · Santiago Trujillo Denunciar

0

Forloop your array $insert_data.

foreach($insert_data as $in_data){
    Model::create($in_data);
}

It should work fine.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda