7

I am trying to achieve the functionality illustrated below:

$table->dateTime('time')->default(new \DateTime());

This exact code is failing, because

[ErrorException]
Object of class DateTime could not be converted to string

The other problem is, that I feel that there should be more robust/elegant way of solving this issue. So, how to correctly set a default DateTime value in migrations?

Gaurav Dave
  • 6,838
  • 9
  • 25
  • 39
Alex Lomia
  • 6,705
  • 12
  • 53
  • 87
  • 11
    I don't understand why this question is marked as duplicate. Timestamp and dateTime are similar but none of the answers tell how to set default value for `dateTime`, not for `timestamp`. To set dateTime default value you can use `Carbon`. `$table->dateTime('time')->default(\Carbon\Carbon::now());` – Mirceac21 Mar 20 '17 at 06:29
  • 2
    @Mirceac21 The challenge with that is it will set it to the actual current time at that moment. This would set it dynamically `$table->dateTime('app_date')->default(DB::raw('CURRENT_TIMESTAMP')); ` – kakoma May 07 '18 at 18:28
  • @Mirceac21 thats a sooo poor approach. You want the current datetime at the moment of insertion, no at the moment the migration is declared! – chesscov77 May 30 '18 at 13:47
  • @Juan @kakoma I thought that the question is about the error thrown by migration when `DateTime` is used. You are both right but it depends on the app needs what "time" to use php or mysql or a fixed date (ex: `Carbon::yesterday()`). The question is how to set default date time not current time. – Mirceac21 May 30 '18 at 18:11
  • You can use $table->dateTime('time')->default(date('Y-m-d h:i:s')) – Pawan Verma Nov 28 '22 at 09:35
  • as in `$table->dateTime('time')->default(date("1900-1-1 00:00:00"));`. Looked a long time for this, but everything is about using current time functions – wruckie Mar 19 '23 at 04:12

1 Answers1

8

Try this:

$table->timestamp('time')->useCurrent = true;

See, if that helps.

Edit:

A better way to write the migration is

$table->timestamp('time')->useCurrent();
Shafi
  • 1,850
  • 3
  • 22
  • 44
Gaurav Dave
  • 6,838
  • 9
  • 25
  • 39
  • 1
    why use true? it's required or not? – Muhammad Dyas Yaskur Oct 12 '18 at 03:39
  • 6
    You should be able to just call `$table->timestamp('time')->useCurrent()`. It likely does the exact same thing, but doesn't end the chain, which lets you do e.g. `$table->timestamp('time')->useCurrent()->change()`. This may be from a newer version of Laravel than the one in 2016 though. – Steen Schütt Jul 16 '19 at 07:28
  • i think @SteenSchütt 's way is more elegant....thank you... i just edit Gaurav Dave's answer for others' ease..... – Syamsoul Azrien Aug 23 '19 at 08:03