Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.1K
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!