Arya Basiri
Arya Basiri

Reputation: 177

Laravel put null in created_at and updated_at while inserting new record

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.

Upvotes: 4

Views: 6995

Answers (3)

Andrea Mattioli
Andrea Mattioli

Reputation: 1091

You have to use create method instead of insert method. Create method automatically add timestamp for created_at and updated_at field.

From Rakesh Nandi answer https://stackoverflow.com/a/54302128/3740246

Upvotes: 1

Andranik Petrosyan
Andranik Petrosyan

Reputation: 92

In the Model you should add this code,

public $timestamps = true;

created_at and updated_at will be updated automatically

Upvotes: 2

Risan Bagja Pradana
Risan Bagja Pradana

Reputation: 4674

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.

Upvotes: 6

Related Questions