Search code examples
laravelpivot-tablelaravel-seeding

laravel databse seed pivot table


I've this tables in my Laravel app: Users Books Categories book_category Authors author_book


im seeding my table wth this code:

factory(App\User::class, 50)->create()->each(function ($user) {
    $user->books()
        ->create(factory(App\Book::class)->make()->toArray())
        ->category()
        ->attach([1,2]);
 });

How can I add author too this code for seed? Is there another way?


Solution

  • I'm guessing you want to add a book to every user. Try creating a new factory for books and then attach $user to your $book.

    factory(App\User::class, 50)->create()->each(function ($user) {
        $book = factory(App\Book::class)->create();
        $user->books()->attach($book);
    });