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.
You can do this
DB::table('table')->insert([
'created_at' => Carbon::now()->format('Y-m-d H:i:s');
]);
Have you tried
DB::table('menu_types')->insert([ 'title' => 'Footer', 'description' => str_random(10), 'created_at' => date("Y-m-d H:i:s") ]);
@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.
@phildawson I tried today, it worked. Thanks. It's 7 year old thread, but still alive and helpful to guys like me. Thanks.
@phildawson I believe it's an Eloquent feature, so it only works for the create method in this case ;) That should explain the behaviour
@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);
}
@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!
@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
I'm using laravel 5.3 and 'created_at' => date("Y-m-d H:i:s") works for me.
Please or to participate in this conversation.