Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, Faker - Increment generated dateTime

I'm using Faker package in my Seeder to generate fake data for training events.

Each event has starts_at and ends_at fields. I want to populate the ends_at field with a DateTime that is after the one generated for starts_at, preferably by 1 to 8 hours, or even a fixed 1 hour difference would be fine.

like image 409
Томица Кораћ Avatar asked Dec 08 '22 05:12

Томица Кораћ


2 Answers

here is an easy way to define the ends_at

$starts_at = Carbon::createFromTimestamp($faker->dateTimeBetween($startDate = '+2 days', $endDate = '+1 week')->getTimeStamp()) ;

$ends_at= Carbon::createFromFormat('Y-m-d H:i:s', $starts_at)->addHours( $faker->numberBetween( 1, 8 ) );
like image 170
zak.http Avatar answered Dec 11 '22 08:12

zak.http


Adapting the pattern described in Build APIs You Won't Hate and using the awesome Carbon package, here's how you can do it:

<?php

use Carbon\Carbon;
use Faker\Factory as Faker;

class UserEventsTableSeeder extends Seeder {

    public function run() {
        $faker = Faker::create();

        foreach (range(1, 15) as $index) {
            $startDate = Carbon::createFromTimeStamp($faker->dateTimeBetween('-1 years', '+1 month')->getTimestamp());

            UserEvent::create([
                // ...

                'starts_at' => $startDate->toDateTimeString(),
                'ends_at'   => $startDate->addHours( $faker->numberBetween( 1, 8 ) )
            ]);
        }
    }
}
like image 44
rmobis Avatar answered Dec 11 '22 07:12

rmobis