Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Osman's avatar

How to seed timestamps field?

Hi everyone,

I'm wondering how i can seed the fields 'created_at' or 'updated_at'. I tried Carbon::now(), but that didn't work.

For example:

DB::table('menu_types')->insert([ 'title' => 'Footer', 'description' => str_random(10), 'created_at' => ??? ]);

Thanks in advance.

Best regards.

0 likes
10 replies
bobbybouwmann's avatar
Level 88

You can do this

DB::table('table')->insert([
    'created_at' => Carbon::now()->format('Y-m-d H:i:s');
]);
17 likes
robgeorgeuk's avatar

Have you tried

DB::table('menu_types')->insert([ 'title' => 'Footer', 'description' => str_random(10), 'created_at' => date("Y-m-d H:i:s") ]);
4 likes
phildawson's avatar

@bobbybouwmann @Osman the format isn't needed btw, it'll use that format when toString is called when it's used in a string context.

use Carbon\Carbon;
    DB::table('menu_types')->insert([
        'name' => 'Footer',
        'description' => str_random(10),
        'created_at' => Carbon::now(),
    ]);

I tried Carbon::now(), but that didn't work

The above code should definitely work.

13 likes
narendrakumar's avatar

@phildawson I tried today, it worked. Thanks. It's 7 year old thread, but still alive and helpful to guys like me. Thanks.

bobbybouwmann's avatar

@phildawson I believe it's an Eloquent feature, so it only works for the create method in this case ;) That should explain the behaviour

phildawson's avatar

@bobbybouwmann it's on the Carbon class though so when used as a string it'll be formatted.

echo 'The datetime is ' . Carbon::now();

I've just done an insert test for my sanity and it's fine so not sure what issue @Osman had.

const DEFAULT_TO_STRING_FORMAT = 'Y-m-d H:i:s';
protected static $toStringFormat = self::DEFAULT_TO_STRING_FORMAT;

public function __toString()
{
    return $this->format(static::$toStringFormat);
}

Osman's avatar

@phildawson I think i was pretty clear by explaining my issue. I just wanted to know the proper way to seed the 'created_at' field. That's it.

And btw, you were right too. The format is indeed not needed. Thanks for that!

phildawson's avatar

@Osman I would say it's even easier to do this in the ModelFactory

$factory->define(App\MenuType::class, function ($faker) {
    return [
        'title' => $faker->sentence,
        'description' => $faker->paragraph
    ];
});

Then where you want to seed, say insert 5 generated.

factory(App\MenuType::class, 5)->create();

https://github.com/fzaninotto/Faker

tecnoher's avatar

I'm using laravel 5.3 and 'created_at' => date("Y-m-d H:i:s") works for me.

1 like

Please or to participate in this conversation.