So i had a seeder for Languages Table (LanguageTableSeeder
) as follows:
DB::table('languages')->insert([
'name' => 'English',
'flag' => '',
'abbr' => 'en',
'script' => 'Latn',
'native' => 'English',
'active' => '1',
'default' => '1',
]);
$this->command->info('Language seeding successful.');
But this resulted in created_at
and updated_at
fields to be Null in database. i looked up the pre shipped UsersTabeSeeder
and changed my LanguageTableSeeder
to mach the exact same format:
DB::table('languages')->delete();
$languages = [
[
'name' => 'English',
'flag' => '',
'abbr' => 'en',
'script' => 'Latn',
'native' => 'English',
'active' => '1',
'default' => '1',
],
];
foreach ($languages as $language){
Language::create($language);
}
This also resulted in created_at
and updated_at
fields to be Null which is odd because when i look up at Users Table in my data base they have created_at
and updated_at
fields to be set at the exact time of running the seeder.
So here is my question. Why is this happening? and is it necessary to use:
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s"),
to get filled timestamp when seeding?
Auto timestamp saving is only for Eloquent feature so you need to do manually like below for non eloquent feature
DB::table('languages')->insert([
'name' => 'English',
'flag' => '',
'abbr' => 'en',
'script' => 'Latn',
'native' => 'English',
'active' => '1',
'default' => '1',
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
]);
OR do it eloquently(Like you have seen in auto generated seeds like UserTableSeeder)
$language = new Language();
$language ->name = 'English';
$language->flag' = '',
$language ->abbr = 'en',
$language->script ='Latn',
$language->native ='English',
$language->active ='1',
$language->default ='1',
$language->save();
Why to use carbon? Eloquent serves up Carbon for datetime and timestamp columns. By default it will serve up Carbon for the created_at, updated_at, and deleted_at columns. You can customize this in your models extending Eloquent\Model.
Carbon\Carbon extends \DateTime
, so there is no loss of functionality by using Carbon in favor of DateTime, only more benefit/flexibility.
In users table seeder do this for timestamp. It works for me..
use Carbon\Carbon;
$faker = Factory::create();
$date = Carbon::now()->modify('-2 year');
$createdDate = clone($date);
DB::table('users')->insert([
[
'name' => "XYZ",
'slug' => "xyz",
'email' => "[email protected]",
'password' => bcrypt('secret'),
'bio' => $faker->text(rand(250, 300)),
'created_at' => $createdDate,
'updated_at' => $createdDate
],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With