Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 703
Octoxan Avatar asked Jan 23 '17 13:01

Octoxan


People also ask

What is data seeding in Laravel?

Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.


1 Answers

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.

like image 108
Alexey Mezenin Avatar answered Oct 23 '22 13:10

Alexey Mezenin