Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel put null in created_at and updated_at while inserting new record

Tags:

null

laravel

I don't know why, but when I want to insert something:

users::insert([
    'first_name' => $first_name,
    'last_name' => $last_name,
    'remember_token' => $remember_token,
]);

It just inserts NULL into created_at and updated_at columns. I have tried these:

'create_at' => time(),
'updated_at' => time(),

'create_at' => '',
'updated_at' => '',

'create_at' => TRUE,
'updated_at' => TRUE,

But none of them worked, but just TRUE put 0000-00-00 00:00:00.

like image 297
Arya Basiri Avatar asked Mar 14 '23 02:03

Arya Basiri


2 Answers

In the Model you should add this code,

public $timestamps = true;

created_at and updated_at will be updated automatically

like image 36
Andranik Petrosyan Avatar answered Apr 26 '23 13:04

Andranik Petrosyan


The timestamp columns (created_at and updated_at) will be assigned automatically only if you are using the Eloquent like so:

$user = new \App\User;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->save();

When you are using query builder, you have to created_at and updated_at value by yourself:

DB::table('users')->insert([
    'first_name' => $first_name,
    'last_name' => $last_name,
    'created_at' => \Carbon\Carbon::now(),
    'updated_at' => \Carbon\Carbon::now(),
]);

Hope this will solve your issue.

like image 94
Risan Bagja Pradana Avatar answered Apr 26 '23 11:04

Risan Bagja Pradana