null
null

Reputation: 469

How to seed a date field in Laravel 5.3?

I've managed to set up a decent amount of seeding for data that needs to be in the database at launch. Everything was easy and working well until I needed to seed a DATE field with a default date.

I've tried the following...

DatabaseSeeder.php

class SettingsTableSeeder extends Seeder {
    public function run()
    {
        Setting::create([
            'name' => 'Start Date',
            'date' => '2000-01-01'
        ]);
    }
}

In my model I've been told adding this should fix it, but it didn't.

Setting.php

protected $dates = [
    'created_at',
    'updated_at',
    'date'
];

Everytime I go to run the seeder it throws the error:

[InvalidArgumentException]
The separation symbol could not be found
Unexpected data found.
Trailing data

If I remove the quotes around the date it changes to..

[InvalidArgumentException]
The separation symbol could not be found
Data missing

Any idea how one goes about seeding a default value for a DATE database field?

Upvotes: 10

Views: 17821

Answers (4)

omkar
omkar

Reputation: 67

$dates= [            
           ['name' =>'Start Date'],
           
       ];

       foreach ($dates as $date) {
           Setting::create($date);
       }

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

If date is in the $dates array, insert Carbon instance instead of a string:

Setting::create([
    'name' => 'Start Date',
    'date' => Carbon::parse('2000-01-01')
]);

You'll need to make sure that Carbon is available to use at the top of the file:

use Carbon\Carbon;

It is auto-loaded by Laravel/Composer.

Upvotes: 12

null
null

Reputation: 469

The given answers by Alexey Mezenin and Jaymin Panchal both still resulted in the trailing data error being thrown.

What ended up working for me was including...

use Carbon\Carbon;

at the top of the DatabaseSeeder.php file.

Then changing my Setting::create to...

DB::table('settings')->insert([
    'name' => 'Start Date',
    'date' => Carbon::create('2000', '01', '01')
]);

for some reason I can't use Carbon with the standard Model::create method while seeding, but it works for DB::table('table')->insert.

Upvotes: 1

Jaymin Panchal
Jaymin Panchal

Reputation: 2856

Just try inserting the date using Carbon like,

class SettingsTableSeeder extends Seeder {
   public function run(){
      Setting::create([
        'name' => 'Start Date',
        'date' => \Carbon\Carbon::createFromDate(2000,01,01)->toDateTimeString()
      ]);
   }
}

Upvotes: 1

Related Questions