Search code examples
laravel-5eloquentlaravel-seedingfactories

Laravel Factories - How to save nested relationships


I was working with laravel factories and stuck with nested relation ships. For example a user may have many posts and a post has many comments. i was able to save posts with user by each() method but was not able to save comments with posts

$users = factory(App\User::class, 3)->create()
    ->each(function ($user) {
        $user->posts()->saveMany(factory(App\Post::class, 5)->make());
    });

as save() method accepts array so i must have to use make() method with posts but now i can't attach comments with the posts. after hour of searching i could not fond the solution but now i have solved it. I am posting it in answers for the fellows who are looking for the solution and please update me if there have more decent solution to this. Thanks


Solution

  • Here is how i solve this:

    $users = factory(App\User::class, 3)->create()
            ->each(function ($user) {
                $user->posts()->saveMany(factory(App\Post::class, 5)->make());
            });
    foreach ($users as $user){
      foreach ($user->posts as $post){
        $post->comments()->saveMany(factory(App\Comment::class, 5)->make());
      }
    }