Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I randomize the number of related records in Laravel seeders
    Laravel random records database seeding factories random_int sequence method


How can I randomize the number of related records in Laravel seeders


To randomize the number of related records when seeding data in Laravel, you can use the `random()` helper function in your factories. Here's how to do it:

php
// Create a category with a random number of posts between 1 and 5
Category::factory()
    ->has(Post::factory()->count(random_int(1, 5)))
    ->create();

// Create 10 categories, each with a random number of posts between 1 and 5
Category::factory(10)
    ->has(Post::factory()->count(random_int(1, 5)))
    ->create();

In this example, when creating a category, it will generate a random number of posts between 1 and 5 for each category. When creating multiple categories, it will generate a random number of posts for each category.

The `random_int()` function generates a random integer between the specified range (inclusive). You can adjust the range to suit your needs.

Another option is to use the `sequence()` method in your factories to cycle through a set of values for the number of related records:

php
// Create 10 categories, cycling through 1, 2, 3 posts per category
Category::factory(10)
    ->has(Post::factory()->count(
        sequence(1, 2, 3)
    ))
    ->create();

This will create 10 categories, with the first category having 1 post, the second having 2 posts, the third having 3 posts, and then repeating the cycle.

By using `random_int()` or `sequence()` in your factories, you can introduce more realistic and varied data when seeding your database with related records in Laravel.

Citations:
[1] https://laraveldaily.com/post/laravel-seeding-hasmany-with-multiple-levels
[2] https://laracasts.com/discuss/channels/laravel/how-to-generate-predictable-random-data-with-database-seeder
[3] https://dev.to/kazemmdev/laravel101-a-practical-guide-for-seeders-and-factories-535b
[4] https://laracoding.com/creating-a-model-with-relations-using-a-laravel-factory/
[5] https://laraveldaily.com/post/laravel-belongstomany-seed-data-factories