Query builder not inserting timestamps
41,044
Solution 1
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()
));
Solution 2
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'),
));
![Samundra Khatri](https://i.stack.imgur.com/9rm2n.png?s=256&g=1)
Author by
Samundra Khatri
I find myself very passionate about CS, loves reading tech books. I love to see and play with the things I build on my own mostly. Things I build are the things I care about most in this world.
Updated on January 19, 2020Comments
-
Samundra Khatri over 4 years
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, ));
-
Samundra Khatri over 8 yearsisn't there any way by which it can be done automatically
-
voodoo417 over 8 years@Samundra KC do you want use only QueryBuilder?
-
Fatih Koca over 5 yearsUse Laravel Macros: medium.com/fattihkoca/…
-
James Bond about 3 years"It works every time" - as long as you have an equal timezone in the DB and PHP ;)