---
title: Controlling randomness in Laravel (watch me code)
url: "https://aaronfrancis.com/videos/controlling-randomness-in-laravel-watch-me-code"
path: "/videos/controlling-randomness-in-laravel-watch-me-code"
type: video
author: Aaron Francis
published: 2024-06-17
topic: "Laravel & PHP"
keywords: [random value generation, mersenne twister, seeding randomness, laravel str random, laravel lottery, predictable randomness, benchmarking, repeatable random strings, php random, testing randomness, lottery class, random string generation]
youtube_url: "https://www.youtube.com/watch?v=4zPd-LDSgGM"
site_index: "/llms.txt"
keyword_index: "/llms/keywords.txt"
---

# Controlling randomness in Laravel (watch me code)

## Chapters

- Introduction to Benchmarking and Random Value Generation
- Introduction to Mersenne Twister and Seeding Randomness
- Example of Repeatable Random Values with Mersenne Twister
- Wrapping Randomness Control in Laravel
- Creating Predictable Random Strings
- Generating Repeatable Random Strings
- Controlling Lottery Results with Predictable Randomness
- Modifying Lottery Class for Seeding Randomness
- Testing and Verifying Lottery Randomness
- Improving and Resetting Randomness for Benchmarking
- Refactoring for Global Seeding and Control
- Debugging and Stabilizing Randomness for Multiple Calls
- Finalizing Predictable Randomness for Benchmarks
- Considering Edge Cases and Final Thoughts
- Conclusion and Feedback Request

## Transcript

**Aaron Francis:** I'm doing a little bit of benchmarking for the SQLite course that I have coming up, highperformancesqlite.com. It is going to be very good. What I need from these benchmarks is I need, like, a million random values, but when I'm comparing two things, I kind of want the random values to all be the same, which is not random, actually. So what I'm looking for is, um, a random generator that is...

**Aaron Francis:** produces repeatable randomness, and I can change it. So I can... If I wanna run a new benchmark, I can just change the random values. We can do that in Laravel. Let me show you how. The two things I wanna control, lottery odds, let's say, we'll just make it five out of 10, choose 10 times. So this, this gives you a random yes, no, on, off, and it...

**Aaron Francis:** You can use it to control certain, certain things. So if I were to run this over here, random, you'll see a bunch of trues, a few falses, a true, and some falses, but if you run it again, it is random. That's the whole point of a lottery, is to choose at random. The other thing I want to cons- want to control is this one right here.

**Aaron Francis:** So if we wrap that guy up and we say, I want that to be repeatable. Now, you can pass through, like, a, a sequence of random values to some of these helpers, and it will choose from that sequence. I don't wanna do that, 'cause I want literally, like, a million random values, and I don't wanna construct a million random values.

**Aaron Francis:** I just want them to be repeatable. Let's figure out how. The first thing I'm gonna show you, uh, we're gonna start super basic. So you have this mtsrand thing, and this will let you seed the Mersenne Twister random number generator, and then if you do mt-rand between one and 10, this is always going to come out to the same thing given the same seed.

**Aaron Francis:** So if you run that over and over and over, you get six over and over and over. But if you were to change the seed, the first value is going to be different. And this is great because it's not just, it's not just that, um, it gives you the same number. It just gives you the same way of generating the numbers. So you can see they're still random numbers, but they are predictably random in that for a given seed, you will always get the same output.

**Aaron Francis:** You always get the same first number, the same first four numbers, et cetera. So that is the way that we're going to seed the random number generator, and that is going to serve as the basis for generating predictably random strings and predictably random lottery results. Now, what I don't wanna do is I don't wanna do this globally, 'cause this is gonna mess everything else up.

**Aaron Francis:** Um, so to reset this, you can reset it by just doing a null. And so if we were to change this to dump, so we'll dump one, and then we'll dump another out below. We would expect, uh, we would expect the first one to always be the same. So this should be constant, and this should actually be random.

**Aaron Francis:** So if we clear this and run it again, we should see nine seven, nine three, nine one. So you're always gonna get nine, and then you switch back to a pure random after you reseed the function with a null. So we wanna wrap that up so that we don't pollute anywhere else in the code that is using this random function stuff. So we do need to wrap that up pretty tightly.

**Aaron Francis:** All right. Let's start with, let's start with string. Uh, create random strings using. So there's the sequence where you could just, like, pass in an array. We don't wanna do that. That's, that's no fun. That's nonsense. So thank you, Laravel, for giving us this factory function. So I can say length and then return, uh, we'll just return foo.

**Aaron Francis:** And now if I were to say, let's get rid of all of this, dd strrandom. Make sure we have control. All right. We have control. We are off to a good start. All right. First thing I wanna do, let us seed it predictably. mt_seed_rand with one, and then do some stuff, and then undo that so that we don't muck it up.

**Aaron Francis:** Uh, seed with... There we go. So we're gonna keep that scoped locally, and then we can have a set of characters, and, uh, we'll just recreate, just like that, and then, uh, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z.

**Aaron Francis:** Um, hopefully there's a way to do... I don't wanna make you watch that again. So if we were to do, what is it? Ooh, uh, switch case, screaming snake case. There we go. Hey, you didn't have to watch it. Now we're gonna take that set of characters and then build up a random string based on that. So we can say that string is nothing, and for i equals zero, i is less than, uh, i is less than length, i plus, plus.

**Aaron Francis:** And then in here, we are going to say... What are we gonna do? Let's do, let's pick a, uh, let's do string.equals. Uh, we need to pick a random value out of, so we'll say characters, and then we're gonna grab from zero to strlen characters less one.

**Aaron Francis:** That's not right. Um, we want characters, uh, mt_rand with those. That should pick a random character out of that string and append it. Let's see if we're close. So does this, um, let's call, yeah, string random down here. We can just return it.

**Aaron Francis:** So we'll return string And let's see. Hey, look at that. It worked. That worked first try, literally first try. That's kinda awesome. Feeling good. Um, all right, so we have a repeatable random string.

**Aaron Francis:** What happens if we call it a couple of times? I think if we call it a couple of times, um, within the same, you know, life cycle, we're gonna see... Ah, it's a little bit too repeatable, isn't it? Got too excited about that working first time thing. Um, okay. So the reason that that happened is we reset... Actually, we didn't. Um, we reset and, but we fully set it in the first place, so it's always being set to one, so it's always going to generate the same string.

**Aaron Francis:** So let's say static seed equals, ooh, yeah, one, and we'll seed it with seed. And before we reset, so that it is still predictable, we're gonna grab a new number to be the seed the next time, and then we will reset it. So first time around, we're gonna set seed to one, and then, uh, seed the random number generator with one, build up a random string, and then we'll reset the seed the next

**Aaron Francis:** time. So if that worked, predictable but still random. And if, for your edification, if we were to dump seed, you see that the seeds always stay the same because we're using the seeded number generator to generate our next seed, which I gotta, gotta, gotta admit, that's kinda awesome.

**Aaron Francis:** Um, okay. I feel like that's good. That seems, um... The only thing we don't have here is I don't have the ability, I don't have the ability to manually set the seed. So, like, once I'm done running the benchmark with this set of data, I don't wanna come in here and be like, "All right, let's try it with a different set of data and see if it's any different." So I'll need to think about that.

**Aaron Francis:** We'll have to figure that out. I think that that is fixable. Um, I think what I'm gonna probably do is set the seed somewhere globally and then pull it in for, for this function. But let's keep going. Let's look at the lottery class now. Let's go poke around in the lottery class. We've got lottery, uh, set result factory, which I think is what we're looking for. This sets a static result factory used to determine the lottery results.

**Aaron Francis:** That is exactly what we're looking for. And what is the result factory by default? Um, we need to find... This looks like the... Yep. So the result factory will give back the static, or it'll give this closure. So I think this is a good place to start. Let's start with that as our result factory.

**Aaron Francis:** Um, so it looks like it takes chances and out of. So chances and out of. Um, so we can return out of equals null, and then they're using random int, which is not seedable. So what we're gonna do, mt_rand, mt_rand.

**Aaron Francis:** Uh, so we're just gonna change that, and then we're gonna do something similar here. Uh, we're gonna set the seed, and then reset it and unset it. So then, uh, result is going to equal that, and return result. So I think this should work.

**Aaron Francis:** Um, we've changed it to use the seeded random function. We've seeded it. We're setting it. We're reseeding it. We're unseeding it. We're returning. All right, cool. Let's, um, let's do lottery odds are... Let's do 3 out of 10, choose 10 times.

**Aaron Francis:** So if we clear this out, and then... All right, so what are the true ones? Three and seven. I think that's it. Uh, so three and seven, three and seven, three and seven. Cool. We've done it. We have successfully controlled the randomness. Let's wrap this up.

**Aaron Francis:** Um, let's wrap this up into something a little bit nicer. Let's say, uh, we wanna put @macro. I would put these individually as macros, but lottery, the lottery class isn't macro-able, um, which is kind of surprising, but that's fine.

**Aaron Francis:** Uh, so we'll say initial, initialize, uh, repeatable randomness. That's nothing if not verbose. Um, and then here's an idea. Um, why don't we pass a seed through here? This is, this is kinda clever.

**Aaron Francis:** I'm not gonna lie. Um, initialize repeatable randomness, and let's put both of these guys, let's put both of these guys in here. And so now these are not gonna be set unless you call initialize repeatable randomness. And, um, r- let's call this one reset randomness.

**Aaron Francis:** Uh, let's stick with the, stick with the verbose. Re- re- re- re-, reset repeatable randomness, and we'll close that out. And what we can do here is say lottery determine. Yep, and str create normally. And all that this is gonna do is it's just gonna, it's just gonna null out those, um...

**Aaron Francis:** It's gonna null these out. So if we determine, it sets the factory to null. And if we look at create normally, it sets the string factory to null. So this will undo everything that we've done down below, but I just had a great idea. All of my ideas are... Nah, that's not true. They're not all great. This one is great. So, um- Something I was saying earlier is there's no way to re-seed this.

**Aaron Francis:** Uh, so, like, if I wanted to move on to a new dataset, there's no way to re-seed it. Uh, but now there is. So instead of, um, instead of setting, hard coding it to one, what we can do is seed the randomness out here, seed the randomness out here, and then we're gonna scroll down and re-seed it to zero, mtsran or rather to null.

**Aaron Francis:** And then what we can do is, in here, we can get a... We can start with a random seed. Uh, no, we want a random seed between... I don't care. Um, is that right? Why is that not right? Oh, it's not allowed as a static initializer.

**Aaron Francis:** Ah, bummer. Um, seed equals null. Um, seed equals seed. I think that should do it. So what I've done here is, um, I'm first going to seed the random number generator with the seed that I pass in.

**Aaron Francis:** Uh, that should go away. With the seed that I pass in, and then inside here, I'm picking a random number, but it's seeded, so it's gonna be the same random number every time, as long as the seed doesn't change. Um, and then I, I re-seed it. Yeah, yeah, yeah, yeah, yeah, yeah. I re-seed it with that random. All right, so let's do that down here as well.

**Aaron Francis:** Um, so I think that is right. Um, I don't know where my s... What did I d- I deleted the wrong thing. Uh, yeah, so let's seed this there. Yep, that's good. Seeds, MT and MT.

**Aaron Francis:** Yeah. Okay. So with any luck, um, let's do this. Let's say, um... Well, let's first prove that we've undone everything. So string random of sixteen and lottery. Let's just say one out of two and choose, um, six.

**Aaron Francis:** So let's clear this out. So we get, um, we get YRT and a bunch of trues in the middle, and then, yep. So we're back to, we're back to fully random. We're back to fully random. So we've undone everything. Then app, uh, what's the name of this function? Initialize repeatable randomness with no seed because seed should default to one, and then let's see if we get repeatable randomness.

**Aaron Francis:** HIZ, and then true, true, false, true, true. No, we didn't. We didn't get repeatable randomness. This is interesting. I wonder why. Um, okay, so let's say, let's say we've seeded it. Ah, I know exactly why. I know exactly why.

**Aaron Francis:** Um, we need to set the seed while it is seeded . Okay, this is insane. Um, okay, I know exactly why this didn't happen, because all we did here is we set the seed. We registered these functions, and then we unset the seed, but we never called the functions.

**Aaron Francis:** So, um, which means that these seeds inside of here never got set, and when it did come time to set it, we're using an unseeded random function. So all we need to do down here is say, uh, strrandom, and lottery, we can just make up. Uh, choose, no, lottery odds, doesn't matter.

**Aaron Francis:** Uh, choose. And that should seed the static or that should set the static seed inside of there. So if we clear that out, and KD, and then a bunch of trues and a false. KD. Oh, no, lottery didn't work. Um, so the string worked. The string worked, but the lottery didn't work.

**Aaron Francis:** It seems like, it seems like the lottery is not working. Let's see if we can figure out why the lottery is not working. I wonder if it's because I... Uh, that doesn't seem like it should be it. No, no, no. Okay. So that's not it at all. What did I do wrong in the lottery function?

**Aaron Francis:** Got it. Got it. Here's the problem. Um, okay, so we have to follow the seeding of the random thing. I seed the random up here with the given seed, then all I do is register some functions, right? All I do is register some functions, and then I call those functions, and then I reset the seed to be nothing.

**Aaron Francis:** The problem is, when I call this strrandom function, what does it do? It resets the seed to be nothing, and then by the time I choose lottery odds, we're back to a fully random number up here because the seed has been deleted. So all I need to do to fix this is seed it, re-seed it, and then we're off to the races.

**Aaron Francis:** So let's do, yep, uh, one out of two, choose six. This should make lottery stable. True, false, false, true. True, false, false, true. True, false, false, true. Okay. And it should make strrandom stable as well. Yep, yep, yep. True, false, false, true.

**Aaron Francis:** True, false, false. Cool. Cool, cool, cool. Now, this should change it, but make it stable still. So it definitely changed it. We went from KD to HY, and we went true, bunch of false, true, but it should be stable. HY, true, bunch of false, true. Cool. Okay.

**Aaron Francis:** Um, and then if we were to app, um... Why did I name them so long? Reset repeatable random. These should all be random for real. So we should see a set of stable ones, I'm just gonna choose three, and then a set of fully random ones.

**Aaron Francis:** Um, HY is stable, QV is random. HY is stable, I7 is random. Yep, we did it. So we fully encapsulated it. The only thing that we haven't really done, um, is if, if somebody else has seeded the random number generator, we're gonna, by registering this, we're gonna come in and basically wipe that out, um, null it out.

**Aaron Francis:** I don't know, man. I think I'm fine with that. I don't think I need to re-seed it back to what it could potentially be seeded to. Um, but if you disagree, let me know in the comments. There might be a way to read the seed out. Gosh, is there a way? Is there a way to get the seed out? Oh, my goodness. Um, seed it, seed it.

**Aaron Francis:** Generate, generate. No, I don't think there's a way to get the seed out no matter what. So alias of mt_srand, mt_srand. Yeah, there's no way to get it back out. So we're just gonna leave it there. I think that is tidy enough for me. Um, the one edge case we're, we're leaving wide open, that's fine with me.

**Aaron Francis:** Um, hopefully you enjoyed this. It's kind of a, another code with me style video. Let me know if you like the code with me style videos. Until the next time, see ya.

---

## Related on aaronfrancis.com

- [Make 5x faster outbound requests in Laravel](/writing/make-5x-faster-outbound-requests-in-laravel) *(Article · 2024-11-22 · shared: benchmarking)*
- [Benchmarking, Type Systems, and Good Hustle](/podcast/benchmarking-type-systems-and-good-hustle-zvir34) *(Podcast · 2023-05-11 · shared: benchmarking)*
- [Make faster outbound requests with Laravel (10x faster, actually)](/videos/make-faster-outbound-requests-with-laravel-10x-faster-actually) *(Video · 2024-04-30 · shared: benchmarking)*

## Relevant Resources from Aaron Francis

- **[Solo](https://soloterm.com)** (overview on site: [/software](/software)): All-in-one agentic development platform and terminal workspace built by Aaron Francis for orchestrating processes and AI coding agents.

## Search aaronfrancis.com (2-Hop Static Keyword Index)

Pick the alphabetical shard matching any topic to find exact pages across all articles, newsletters, videos, talks, and podcast transcripts (every shard is < 40 KB):
[A-B](/llms/keywords/a-b.txt) · [C](/llms/keywords/c.txt) · [D-E](/llms/keywords/d-e.txt) · [F-G](/llms/keywords/f-g.txt) · [H-J](/llms/keywords/h-j.txt) · [K-L](/llms/keywords/k-l.txt) · [M-N](/llms/keywords/m-n.txt) · [O-P](/llms/keywords/o-p.txt) · [Q-R](/llms/keywords/q-r.txt) · [S](/llms/keywords/s.txt) · [T-Z](/llms/keywords/t-z.txt) · [Directory](/llms/keywords.txt) · [Site Map](/llms.txt)

Shards for this page's topics: `random value generation` ([Q-R](/llms/keywords/q-r.txt)), `mersenne twister` ([M-N](/llms/keywords/m-n.txt)), `seeding randomness` ([S](/llms/keywords/s.txt)), `laravel str random` ([K-L](/llms/keywords/k-l.txt)).

## About Aaron Francis (Current Context)

Aaron Francis is VP of Marketing and Community at [Laravel](https://laravel.com), founder of [Try Hard Studios](https://tryhardstudios.com), creator of [Solo](https://soloterm.com), co-host of [Mostly Technical](/podcast), and author of [Mastering Postgres](/courses), [High Performance SQLite](/courses), [MySQL for Developers](/courses), and [Screencasting.com](/courses). Full bio: [/about](/about) · Current focus: [/now](/now).
