A Laravel factory with starting and ending dates

Publié le 04/01/2016 | #laravel , #php

Laravel provides a convenient way to seed your database with fake data for testing purpose using a system of factories for your Eloquent models. vh This is a demonstration of how to create a factory for a model that is using starting and ending dates, like a Workshop model for example.

First we need a starting date that would be useful for the tests: one that’s not already past and yet not too far in the future because you might filter the whorkshops in your code to only display relevant informations. The great faker library comes to help by providing a few date-related functions like dateTimeThisYear() to which you can pass a string that will be interpreted by strotime(): $faker->dateTimeThisYear('+1 month'). You can then use strotime() to generate an endind date at a specific time after the starting date: strtotime('+1 Week', $startingDate->getTimestamp()).

The factory will look like:

$factory->define(App\Workshop::class, function (Faker\Generator $faker) {
    $startingDate = $faker->dateTimeThisYear('+1 month');
    $endingDate   = strtotime('+1 Week', $startingDate->getTimestamp());

    return [
        'starting_date' => $startingDate,
        'ending_date'   => $endingDate,
        // ... other model attributes

You may also want to generate whorkshops for, say, the current week, by using the faker method dateTimeBetween():

$factory->defineAs(App\Working::class, 'this_week', function (Faker\Generator $faker) use ($factory) {
    $activity = $factory->raw(App\Activity::class);
    // Random datetime of the current week
    $startingDate = $faker->dateTimeBetween('this week', '+6 days');
    // Random datetime of the current week *after* `$startingDate`
    $endingDate   = $faker->dateTimeBetween($startingDate, strtotime('+6 days'));

    return array_merge($activity, [
        'starting_date' => $startingDate,
        'ending_date'   => $endingDate,