Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mikeritter's avatar

Unique dates with faker

Faker is giving me duplicate dates with the unique flag:

'date' => $faker->unique()->dateTimeBetween($startDate = "now", $endDate = "30 days")->format('Y-m-d')

I'm guessing it's considering the date + time is unique, but I want the resulting date to be unique.

Any ideas?

0 likes
1 reply
usman's avatar

Hi, IMHO, you can also use Carbon to generate the random dates e.g:

$date = new Carbon\Carbon();
for($i = 1; $i<=20; $i++)
{
    $randomDays = mt_rand(1,31);
    $date->addDays($randomDays);
    echo $date->toDateString().PHP_EOL;//just for output in tinker
}

Here is the output:

2014-11-25
2014-12-09
2015-01-06
2015-01-26
2015-02-04
2015-02-21
2015-03-08
2015-03-22
2015-03-28
2015-04-23
2015-05-18
2015-06-06
2015-06-09
2015-07-03
2015-07-29
2015-08-15
2015-08-27
2015-08-28
2015-09-08
2015-10-04

I am not sure :( if this suits your needs. Just an opinion. Thanks!

Please or to participate in this conversation.