Skip to content
This repository has been archived by the owner on Dec 11, 2020. It is now read-only.

Suggestion - Faker method to randomly execute #2046

Open
pnoeric opened this issue Aug 17, 2020 · 1 comment
Open

Suggestion - Faker method to randomly execute #2046

pnoeric opened this issue Aug 17, 2020 · 1 comment

Comments

@pnoeric
Copy link

pnoeric commented Aug 17, 2020

I'm using Faker with Laravel to populate a field that 70% of the time should have a random date, and the rest of the time it should be null. Here's how I do it now:

// 70% of the time set a date, otherwise it's null
'LastNudgeEmail' => (mt_rand(1, 10) > 3) ? $faker->dateTimeBetween("now", "+1 month") : null

I was thinking that it'd be cool if Faker had a new chainable method that would only pass along the chain if a % threshold was met; if it didn't pass, Faker would just return the value specified in the method call. So the above code could become a little more elegant and readable:

// 70% of the time set a date, otherwise it's null
'LastNudgeEmail' => $faker->chanceOfPassing(70, null)->dateTimeBetween("now", "+1 month")

(There's probably even a more elegant name/way to set up the method and its parameters... but you get the drift...)

@patrickdaze
Copy link

Maybe the optional() modifier?

'LastNudgeEmail' => $faker->optional(70)->dateTimeBetween('now', '+1 month')

Source code for optional()

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants