Adding Relations to Laravel Factory Model

Adding Relations to Laravel Factory Model

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Adding Relations to Laravel Factory Model

When seeding your database, you often need to establish relationships between models. A common stumbling block arises when attempting to use saveMany() or save() on a collection generated directly from a factory call. The specific error Argument 1 passed to ...HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given indicates a fundamental misunderstanding of how Laravel's Eloquent relationships and factories interact.

The issue stems from the type returned by the factory method. When you invoke factory(App\Post::class, 2)->make(), you are not creating two separate model instances that you can pass individually to a relationship. Instead, the factory returns an Illuminate\Database\Eloquent\Collection. The save() method on a relation expects a single Model instance, not a collection. Passing a collection triggers the type mismatch error seen in the logs.

To resolve this without resorting to repetitive code like calling save() ten times for ten posts, you must align the factory output with the relationship expectation. The most direct approach is to use the saveMany() method instead of save(). This method accepts a collection and persists all models within it in a single query operation.

public function run()
{
    factory(App\User::class, 50)->create()->each(function($u) {
        $posts = factory(App\Post::class, 2)->make();
        $u->posts()->saveMany($posts);
    });
}

By switching to saveMany(), you maintain the elegance of defining the quantity once (factory(App\Post::class, 2)) while satisfying the strict typing requirements of the relationship manager. This approach scales perfectly; if you need ten posts, simply change the count to ten, and Laravel handles the batching internally.

The situation becomes more complex when nesting relations deeper, such as creating posts that each have comments. The original attempt in the source material tried to nest save() calls inside a factory iteration, which is syntactically incorrect because make() returns a collection, not an iterable list of models ready for immediate save chaining on the relation.

To handle nested relations like User -> Post -> Comment, you cannot simply chain ->comments()->save(...) inside the innermost factory loop in the way shown. The factory() method does not automatically hydrate and save child relations based on the parent's state when using make(). Instead, you should construct the data structure manually or use a different strategy to ensure the foreign keys are set correctly before saving.

The most robust pattern for deep nesting involves creating the models in reverse order of dependency or explicitly setting the relationship properties before calling save. However, if you want to leverage factory syntax for the comments within the post creation, you must ensure the collection is handled correctly.

public function run()
{
    factory(App\User::class, 50)->create()->each(function($u) {
        $posts = factory(App\Post::class, 2)->make();
        
        foreach ($posts as $post) {
            // Create a collection of comments for this specific post instance
            $comments = factory(App\Comment::class, 1)->make(); 
            // Explicitly set the foreign key if necessary, though usually handled by factory state
            
            // Save the single comment to the specific post relation
            $post->comments()->saveMany($comments);
        }
        
        // Finally save the posts themselves to their user
        $u->posts()->saveMany($posts);
    });
}

In this revised structure, we iterate over the collection of posts returned by make(). For each individual post instance (which is now an Model object, not a collection), we can successfully call $post->comments(). We then create a new collection of comments and pass it to saveMany() on that specific relation.

This pattern avoids the "nested save" ambiguity. It ensures that:

  1. The outer loop creates users.
  2. The middle layer creates posts and associates them with the user via saveMany.
  3. The innermost layer iterates over individual post instances to attach comments.

Attempting to nest factories three levels deep in a single chained call often leads to confusion regarding which collection is being passed to which relationship manager. Separating the creation of the immediate relation's collection from the nested relations ensures clarity and prevents runtime errors. This approach keeps your database seeding logic predictable, performant, and easy to debug as your application complexity grows.

Our network