Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple level factory for database seeding to work

Tags:

php

laravel-5

So i'm trying to get factories setup to allow for random seeding of a test database. I want to be able to have a bunch of users created, who then create a bunch of rooms, and then post comments to the rooms.

This is what I have:

factory('App\User', 5)->create()->each(function($u) {
    $u->rooms()->save(factory('App\Room', 10)->create()->each(function($p) {
        $p->posts()->save(factory('App\Post', 10)->make());
    }));
});

I get the following error:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given

I assume that the error means that it's not creating the rooms before it tries to create the posts?

like image 574
Michael Dodwell Avatar asked Oct 29 '25 13:10

Michael Dodwell


1 Answers

Perhaps a bit late, but you have to call saveMany(...) instead of save(...) as described in the Eloquent documentation

Indeed, you want to create more than one object (factory('App\Room', 10)->create() or factory('App\Post', 10)->make()), which return a Collection (in short words, an array of objects)

A special thank to a friend, who reminds me to RTM ^^

like image 113
m4as Avatar answered Oct 31 '25 02:10

m4as