Skip to content

Instantly share code, notes, and snippets.

@rcubitto
Last active March 12, 2019 09:41
Show Gist options
  • Save rcubitto/902cc6224826d7c18aedb80dfa828687 to your computer and use it in GitHub Desktop.
Save rcubitto/902cc6224826d7c18aedb80dfa828687 to your computer and use it in GitHub Desktop.
Model factories chain example
  • Comment BELONGSTO Post
  • Comment BELONGSTO User
  • Post BELONGSTO User
  • Post BELONGSTOMANY Category
  • Category BELONGSTO User

When you call

factory(\App\Comment::class)->create();

It will generate a Comment, Post, Category. All belonging to the same User. The Category will also be related to the Post.


P.S. Depending on the scenario, I'd consider using something more organized like "Model Factory Stories" https://github.com/jeffochoa/factory-stories

<?php
use Faker\Generator as Faker;
$factory->define(App\Category::class, function (Faker $faker) {
return [
'user_id' => factory(\App\User::class),
];
});
<?php
use Faker\Generator as Faker;
$factory->define(App\Comment::class, function (Faker $faker) {
return [
'post_id' => factory(\App\Post::class),
'user_id' => function ($comment) {
return \App\Post::find($comment['post_id'])->user_id;
}
];
});
<?php
use Faker\Generator as Faker;
$factory->define(App\Post::class, function (Faker $faker) {
return [
'user_id' => factory(\App\User::class)
];
});
$factory->afterCreating(\App\Post::class, function (\App\Post $post, Faker $faker) {
$post->categories()->save(factory(\App\Category::class)->make([
'user_id' => $post->user_id
]));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment