Search code examples
laraveleloquent

Laravel insert not saving created_at, updated_at columns


I have Calendar model. I want to insert mass data.

$data = [
   [
       'weekday' => 1,
       'status'  => 'active'
   ]
   .......
];
$calendar->insert($data)

but in db created_at, and updated_at is null Why??;


Solution

  • If you INSIST on using insert and to update timestamps automatically, Laravel does not offer this.

    you need to do it manually from the code side. as someone mention in some answer as:

    'created_at' => $calendar->freshTimestamp(),
    'updated_at' => $calendar->freshTimestamp()
    

    I faced a similar problem in one project, so I wanted to insert but without adding the timestamps in my code every time I insert so. if you need to use insert without adding the timestamps manually. you can change your migrations file and add the timestamps manuallay:

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

    now the database will handle the created at and updated at on insert.

    the created_at will be equal to the updated_at and equal to the current timestamp

    then on save() laravel will handle updating the updated_at