Query builder not inserting timestamps
Asked Answered
P

3

39

I am using Query builder to insert data all fields are been inserted but timestamps like created_at and updated_at are not inserting they all have default 0:0:0 values my insert query is

$id = DB::table('widgets')
            ->insertGetId(array(
                'creator' => Auth::user()->id,
                'widget_name' => $request->input('widget_name'),
                'pages' => json_encode($request->input('pages')),
                'domain' => $request->input('domain'),
                "settings" => $settings,
            ));
Promisee answered 31/10, 2015 at 13:27 Comment(0)
R
87

All right. Fields created_at,update_at and deleted_at are "part" of Eloquent. You use Query Builder=> inserting doesn't affect on these two fields (created_at and updated_at). You should define it manually like:

$id = DB::table('widgets')
        ->insertGetId(array(
            'creator' => Auth::user()->id,
            'widget_name' => $request->input('widget_name'),
            'pages' => json_encode($request->input('pages')),
            'domain' => $request->input('domain'),
            "settings" => $settings,
            "created_at" =>  \Carbon\Carbon::now(), # new \Datetime()
            "updated_at" => \Carbon\Carbon::now(),  # new \Datetime()
        ));
Regorge answered 31/10, 2015 at 13:42 Comment(3)
isn't there any way by which it can be done automaticallyPromisee
@Samundra KC do you want use only QueryBuilder?Regorge
Use Laravel Macros: medium.com/fattihkoca/…Mcclenon
L
8

In my case, I'm using date('Y-m-d H:i:s'); to get current dateTime. It works every time.

    $id = DB::table('widgets')
        ->insertGetId(array(
            'creator' => Auth::user()->id,
            'widget_name' => $request->input('widget_name'),
            'pages' => json_encode($request->input('pages')),
            'domain' => $request->input('domain'),
            "settings" => $settings,
            "created_at" =>  date('Y-m-d H:i:s'),
            "updated_at" => date('Y-m-d H:i:s'),
        ));
Lewls answered 19/1, 2020 at 7:34 Comment(1)
"It works every time" - as long as you have an equal timezone in the DB and PHP ;)Kenosis
S
2

Another way is to use raw expression and 'CURRENT_TIMESTAMP' as the value assuming the database is a MySQL database.

$now = DB::raw('CURRENT_TIMESTAMP');
$rowID = DB::table('user')->insertGetId([
  'name' => $request->name,
  'updated_at' => $now,
  'created_at' => $now
]);
Soloist answered 19/12, 2022 at 7:12 Comment(2)
This answer is the fastest. When you're mass assigning, Carbon::now() is slower. 110k rows is 15 seconds faster. Thanks!Bise
@Bise if you call Carbon::now() on each of those 110k records, it's understandable that it's much slower. If you call Carbon::now() once and then use that value for those 110k records, it shouldn't matter.Cotinga

© 2022 - 2024 — McMap. All rights reserved.