Search code examples
laravelseeding

How can I attach functions in seeder?


I want to attach authors()

here's my code in UsersTableSeeder

factory(User::class , 10)->create()->each(function ($user){
    $user
        ->books()->create(factory(Book::class)->make()->toArray())
        ->categories()->attach([1,2,3])
        ->authors()->attach([1,2]);
});

but I get the error of 'calling function authors on null'


Solution

  • attach doesn't return the model. You can't do all that inline. Try making it like this:

    factory(User::class , 10)->create()->each(function ($user) {
        $book = factory(Book::class)->make();
        $user->books()->save($book);
        $book->categories()->attach([1,2,3]);
        $book->authors()->attach([1,2])
    });