Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon What are some examples of using the each() method in Laravel seeders
    Laravel seeders each() method random records sequence method Laravel factories database seeding related records


What are some examples of using the each() method in Laravel seeders


here are some examples of using the `each()` method in Laravel seeders:

Randomizing the Number of Related Records

To randomize the number of related records when seeding data, you can use the `random()` helper function in your factories:

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();

This will create categories with a random number of posts between 1 and 5 for each category.

Cycling Through a Set of Values

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.

Associating Related Models

You can also use the `each()` method to associate related models after creating the main model:

php
// Create 5 tasks and associate each with 2 random tags
$tasks = Task::factory(5)->create();
$tasks->each(function ($task) {
    $tags = Tag::query()->inRandomOrder()->take(2)->pluck('id');
    $task->tags()->attach($tags);
});

This will create 5 tasks, and then associate each task with 2 randomly selected tags.

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

Citations:
[1] https://laraveldaily.com/post/laravel-seeding-hasmany-with-multiple-levels
[2] https://dev.to/kazemmdev/laravel101-a-practical-guide-for-seeders-and-factories-535b
[3] https://www.digitalocean.com/community/tutorials/how-to-populate-a-database-with-sample-data-using-laravel-seeders-and-eloquent-models
[4] https://laravel.com/docs/5.4/seeding
[5] https://laracasts.com/discuss/channels/laravel/best-way-to-handle