If a User has many posts, and a post belongs to user, it's simple to do:
$factory->define(App\Post::class, function ($faker) {
return [
'title' => $faker->title,
'content' => $faker->paragraph,
'user_id' => function () {
// Creates a User for every Post
return factory(App\User::class)->create()->id;
}
];
});
How do I accomplish the opposite? Instead, creating say 5 posts when a user is created and associating that post to the newly created user?
~Edit I am using laravel 5.2, and I've declared my model relationships in my models, so I now have:
$user = factory(App\User::class)->create();
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);
// Great, now I have a User and 3 Posts associated with that user.
// However, now, I want let's say, 5 votes per post.
// I can't call $posts->votes(), so I iterate
foreach ($posts as $post) {
$votes = factory(App\Votes::class, 5)->make();
$post->votes()->saveMany($votes);
}
Then any other relation to votes, etc would just be nested in the foreach.
$factory->define(App\User::class, function ($faker) {
return [
'name' => $faker->name,
'email' => $faker->email
];
});
$factory->define(App\Post::class, function ($faker) {
return [
'title' => $faker->title,
'content' => $faker->paragraph
];
});
$user = factory(User::class)->create();
$post = factory(User::class)->create();
$user->posts()->associate($post);
Create 5 fakers in $posts
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);
I would use Model Events for that. In your AppServiceProvider
, add the events as below:
namespace App\Providers;
use App\User;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::created(function ($user) {
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);
});
Post::created(function ($post){
$votes = factory(App\Vote::class, 3)->make();
$post->votes()->saveMany($votes);
});
}
Now you do not have to worry about the automatic creation, also, this should not be part of the Controller logic anyways.