Laravel insert not saved created_at, updated_at columns
Solution 1
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
Solution 2
Because you're inserting data, created_at and updated_at will only be automatically filled if you're using ->save()
.
Make sure you have added those fields to your protected $fillable = [];
array.
You can also use $calendar->update($data)
or
$calendar->fill($data);
$calendar->save();
Hope I understood your question.
Solution 3
One solution is this
$data = [
[
'weekday' => 1,
'status' => 'active',
'created_at' => $calendar->freshTimestamp(),
'updated_at' => $calendar->freshTimestamp()
]
.......
];
$calendar->insert($data)
2 solution In Model
/**
*
*/
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->created_at = $model->freshTimestamp();
$model->updated_at = $model->freshTimestamp();
});
}
Related videos on Youtube
Davit Zeynalyan
I am Davit Zeynalyan. I am a software engineer. I know mysql, c++, php (laravel framework), html, javascript, jquery
Updated on May 28, 2022Comments
-
Davit Zeynalyan almost 2 years
I have Calendar model. I wont to insert mass data.
$data = [ [ 'weekday' => 1, 'status' => 'active' ] ....... ]; $calendar->insert($data)
but in db created_at, and updated_at is null Why??;
-
Kyslik almost 6 yearsBecause in order to have timestamps you need to use
save()
, notinsert()
which is method of query builder not of eloquent model. -
Dev almost 6 yearsIn create array either pass them manually with set them to
$fillable
in model, or just update your migration script like$table->timestamp(’something_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
-
Niklesh Raut almost 6 yearsyour laravel version please ?
-
Davit Zeynalyan almost 6 yearslaravel verion is 5.5
-
-
Davit Zeynalyan almost 6 yearsBy default $timestamps = true; see trait Illuminate\Support\Carbon\HasTimestamps