Seeding data using factory and eloquent models

Posted 8 months ago by elo

I am trying to seed my books and ratings table, and the relationship between them is that a book has many ratings while a rating belongs to a book. I want the each seeded book record to have a rating for each seeded user. Which means if i have only one user and 2 books, my ratings table should have only 2 records.

Unfortunately my code doesn't work like I want it to. I have a situation where one user has multiple rating for each book, how do I achieve my goal of having a user rate a book just once?

This is my code


$factory->define(Book::class, function (Faker $faker) {
    return [
        'title'     => $faker->sentence,
        'author'    => $faker->name,
        'user_id'   => 1

$factory->define(Rating::class, function (Faker $faker) {
    return [
        'user_id'   => 1,
        'book_id'   => mt_rand(1, 2),
        'rating'   => mt_rand(1, 5)


public function run()
        // First remove existing books records

        factory(App\Book::class, 2)->create()->each(function ($book) {
            // Add book rating
            $ratings = factory(App\Rating::class, 1)->create(['book_id' => $book->id]);

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.