4

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Arya Basiri
  • 177
  • 2
  • 14

3 Answers3

6

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.

Risan Bagja Pradana
  • 4,494
  • 1
  • 20
  • 22
2

In the Model you should add this code,

public $timestamps = true;

created_at and updated_at will be updated automatically

1

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

Andrea Mattioli
  • 873
  • 9
  • 9