RECYCLING AN EXISTING MODEL FOR RELATIONSHIPS

Feb 03, 2024 Copy Link

When you work on a project it's IMPORTANT to seed fake data into the database to save your time. No issue when seeding a model that has no relation with another model but, it's so sensitive to seeding a model that is based on another because the data must be fairly real. Come on to take a closer look at these scenarios

 

Imagine that we want to seed the `posts` table with fake data actually, we will use one of the following ways:

 

/**
 * Define the model's default state.
 *
 * @return array<string, mixed>
 */
public function definition(): array
{
    return [
        'title'      => fake()->text(20),
        'body'       => fake()->paragraph(),
        'is_visible' => fake()->boolean(),
        // A first way to get random user
        'user_id'    => User::inRandomOrder()->first()->id,
        // A second way to get random user
        // 'user_id'    => User::all()->random()->id,
    ];
}

 

In the previous code, we seeded the `user_id` column with a random value from an existing users

 

We should seed the `users` table first and then seed the `posts` table.

 

There is another way, where we create a new user for each new post:

 

/**
 * Define the model's default state.
 *
 * @return array<string, mixed>
 */
public function definition(): array
{
    return [
        'title'      => fake()->text(20),
        'body'       => fake()->paragraph(),
        'is_visible' => fake()->boolean(),
        'user_id'    => User::factory(),
    ];
}

 

For the previous two ways, we will write the following code in the `DatabaseSeeder.php` class to seed the `posts` table:

 

/**
 * Seed the application's database.
 */
public function run(): void
{
    // A first way to seed the `posts` table
    Post::factory(10)->create();

    // A second way to seed the `posts` table
    // Post::factory()
    //     ->count(10)
    //     ->create();

}

 

In these ways, we always assign a different user per post.

 

But, what if we need to seed the `users`, `posts`, and `images` tables, where these tables are related to each other and the User who created a Post, is the same as who uploaded the post's Image here, we should seed the same user for each post and image that is created

 

In such a scenario, we need a method such as a recycle method:

 

/**
 * Seed the application's database.
 */
public function run(): void
{
    Image::factory()
        ->recycle(User::factory()->create())
        ->create();
}

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE