Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query builder not inserting timestamps

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,
            ));
like image 836
Samundra Khatri Avatar asked Oct 31 '15 13:10

Samundra Khatri


2 Answers

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()
        ));
like image 192
voodoo417 Avatar answered Oct 13 '22 23:10

voodoo417


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'),
        ));
like image 31
akmoji Avatar answered Oct 14 '22 01:10

akmoji