John Little
John Little

Reputation: 12345

laravel 5.4, how to insert a timestamp (mysql)

In our laravel migrations, we insert static data which is required by the app (countries, currencies etc).

We are trying to insert a row with a timestamp field, but cant figure out how to set it to a specifid day/time.

We have tried time() and setting a standard date format, e.g:

DB::table('test')->insert(['id'=>1,'start_at'=>time(), 'end_at'=>'2050-01-01 00:00:00']);

Both timestamp columns end up with 0000-00-00 00:00:00.

Any ideas?

Upvotes: 2

Views: 9880

Answers (4)

instance
instance

Reputation: 62

You can also let the DB server do the work:

'start_at'=>DB::raw('now()')

Upvotes: 1

Peter Haberkorn
Peter Haberkorn

Reputation: 259

with Carbon:

$dt = Carbon::parse('2012-9-5 23:26:11');
var_dump($dt->timestamp);     //int(1346901971)

Upvotes: 1

John Little
John Little

Reputation: 12345

OK, I found one solution (Carbon option given by Joel & Maraboc might be better)

$now= new DateTime;
$future = $now->add(new DateInterval('P20Y'));
DB::table('test')->insert(['id'=>1,'start_at'=>$now, 'end_at'=>$future]);

Upvotes: 0

Joel Hinz
Joel Hinz

Reputation: 25384

time() returns a Unix timestamp, but MySQL wants a YYYY-mm-dd HH:ii:ss timestamp. You can use e.g. date('Y-m-d H:i:s') or try out Carbon.

By the way, you also have a missing ' prior to start_at.

Upvotes: 3

Related Questions