Model Factory Association With Existing Models

- 1 answer

I have the following structure in my Laravel 5.2 app:

User: id name ...

Post: id title body user_id (fk)

Comment: id body user_id (fk) post_id (fk)

I want to create few users (20), for each users a random number of Posts, and to each post, a random number of comments(even a fixed number it`s ok).

I can create users and assign Posts to each, but i can't assign comments to each post: i have this:

factory(App\User::class, 20)->create()->each(function($u) {
   $u->posts()->saveMany(factory(App\Post::class, 5)->make();

I found something but didn`t work:

factory(App\Comment::class, 100)->create()->each(function($u) {

NOTE: i made the relationship between models like this: User hasMany Post, User hasMany Comment, Post hasMany Comment, Comment belongsTo Post, Comment belongsTo User



You can achieve this by using your factories to nest your next child etc.

You have relationships which are referenced by some fk so to achieve correct 'fk' values you can do the following:

factory('App\Users', 123)->create()->each(function ($u) {

        factory('App\Posts', 1)->create([
            'user_id' => $u->id,
        ])->each(function ($e) use ($u) {
            factory('App\Comments', 10)->create([
                'user_id' => $u->id,
                'post_id' => $e->id,


The arrays in the create method will override the values set in your ModelFactory.php