Laravel 8 factories

Viewed 1475

Can someone tell me how can I make a factory with relationships etc...

I have a post table with 2 foreign keys: user_id and category_id I need to generate dummy data but I don't know how to do it.

I have tried to make categories first then to do something with posts and users but did not work.

PostFactory:

public function definition()
{
    $title = $this->faker->sentence;
    $slug = Str::slug($title);
    return [
        'title' => $title,
        'slug' => $slug,
        'image' => $this->faker->imageUrl(900, 300),
        'content' => $this->faker->text(300),
    ];
}

CategoryFactory:

public function definition()
{
    $category = $this->faker->words(2, true);
    $slug = Str::slug($category);
    return [
        'category' => $category,
        'slug' => $slug
    ];
}

And user factory is just default one :)

1 Answers

You can check if you have enough records, and query the DB to find a random User and Category to use on each Post. But if there not enough records (20 Users and 7 Categories), create a new one.

PostFactory:

public function definition()
{
    $title = $this->faker->sentence;
    $slug = Str::slug($title);
    $user = User::count() >= 20 ? User::inRandomOrder()->first()->id: User::factory();
    $category = Category::count() >= 7 ? Category::inRandomOrder()->first()->id: Category::factory();

    return [
        'title' => $title,
        'slug' => $slug,
        'image' => $this->faker->imageUrl(900, 300),
        'content' => $this->faker->text(300),
        'user_id' => $user,
        'category_id' => $category,
    ];
}
Related