Skip to content

Instantly share code, notes, and snippets.

@amochohan
Created March 6, 2017 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amochohan/aa3eaf01a03a66fe6424bd4f9dcd8539 to your computer and use it in GitHub Desktop.
Save amochohan/aa3eaf01a03a66fe6424bd4f9dcd8539 to your computer and use it in GitHub Desktop.
Model factories - making relationships
<?php
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
'example_id' => function (array $user) {
return factory(App\Example::class)->create()->id;
}
];
});
// Using the following, will cause Eloquent to persist the models to the database
$user = factory(App\User::class)->create();
// An 'Example' will also be created
// However, If I want to just 'make' the instance:
$user = factory(App\User::class)->make();
// An 'Example' will still be created, rather than made.
@amochohan
Copy link
Author

I suppose I could use states, where I override creating the relationship with a make, but that seems a bit of a code smell to me.

@amochohan
Copy link
Author

Actually, the way that model factories work is, they use arrays rather than objects. So, example_id expects an id, not an instance
If I'm making a model, it would not have an id and therefore the factory created model would have a value of null for example_id.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment