Problem filling random date with seeder Laravel 6

Viewed 558

I am filling a database with seeders and factory, the problem is that I need to fill the CREATED_AT field with dates that are not today's date but random, to be able to fill the different graphs that the page has.

I tried and sometimes it inserts data and other times it throws error that the field is invalid and that is in date format the error that throws me in the console.

ERROR MESSAGE
"Incorrect datetime value: '2021-09-05 00:00:00' for column 'created_at' at row 1"

Error image

CODE

$factory->define(Opportunity::class, function (Faker $faker) {
    $account_id = Account::all()->random()->id;
    $account    = Account::find($account_id);
    $contact    = Contact::where('account_id',$account_id)->inRandomOrder()->limit(1)->first();
    $created    = $this->faker->dateTimeBetween($startDate = '-3 month', $endDate = 'now +6 month');
    $date = strtotime('+2 days', strtotime(Carbon::parse($created)));

    return [
        'created_at'    => Carbon::parse($created)->format('Y-m-d H:i:s'), ///line error
        'name'          => $this->faker->name .' '.$this->faker->sentence(2),
        'amount'        => $this->faker->numberBetween($min = 120000, $max = 20000000),
        'probability'   => $faker->randomElement(['0','10','20','30','40','50','60','70','80','90','100']),
        'description'   => $this->faker->paragraph,
        'lead_source_id'=> LeadSource::all()->random()->id,
        'sales_stage_id'=> 1,
        'account_id'    => $account_id,
        'user_id'       => $account->user_id,
        'contact_id'    => ( $contact != null ? $contact->id : null),
        'close_date'    => Carbon::parse($date)->format('Y-m-d'),
        'product_line_id'=> ProductLine::all()->random()->id
    ];
});
1 Answers

Try by changing $this->faker to $faker and migration should have $table->timestamps();

then u can use dateTimeBetween directly like this

'created_at'=>$faker->dateTimeBetween($startDate = '-3 month',$endDate = 'now +6 month')

OpportunitySeeder Class

public function run()
{
    factory(App\Opportunity::class,5)->create();
}

DatabaseSeeder class

  $this->call([
        OpportunitySeeder::class
  ]);

https://laravel.com/docs/6.x/database-testing#using-seeds

Related