Let’s take a look at this piece of code and understand it step by step:
Book::factory(33)->create()->each(function ($book)
{
$numReviews = rand(5, 50);
Review::factory()->count($numReviews)->good()->for($book)->create();
});At first glance, it might look confusing—but don’t worry. We’ll break it into small pieces.
🧩 What This Code Does (In Simple Words)
👉 It:
- Creates 33 books
- For each book:
- Generates a random number
- Creates that many good reviews for the book
🔍 Step-by-Step Breakdown
1. Book::factory(33)
This tells Laravel:
👉 “I want to create 33 fake books.”
2. ->create()
Book::factory(33)->create();👉 This actually saves those 33 books into the database.
It returns a collection (a list) of those books.
3. ->each(function ($book) { ... })
Now Laravel loops through each book one by one.
👉 Think of it like:
“For every book, run this function.”
Inside the loop:
$book= current book
4. $numReviews = rand(5, 50);
This generates a random number between 5 and 50.
👉 So each book will have:
- Minimum 5 reviews
- Maximum 50 reviews
5. Review::factory()
Starts creating a factory for reviews.
👉 “Now I want to create fake reviews.”
6. ->count($numReviews)
->count($numReviews)👉 “Create this many reviews.”
Example:
- If
$numReviews = 12, it creates 12 reviews
7. ->good()
This is your custom factory state.
👉 It ensures:
- Ratings are only 4 or 5
So all reviews created here are positive reviews.
8. ->for($book)
This is very important.
👉 It links each review to the current book.
In database terms:
- Sets
book_idin reviews table
So each review belongs to that specific book.
9. ->create()
Finally:
👉 Saves all those reviews into the database.
🧠 Putting It All Together
For each of the 33 books:
- Generate a random number (5–50)
- Create that many reviews
- Make sure reviews are “good”
- Attach them to the correct book
✅ Final Thoughts
This one line of code is very powerful because it combines:
- Factories
- States (
good()) - Relationships (
for($book)) - Loops (
each())
Once you understand this pattern, you can build complex test data easily.
