Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

amochohan commented Mar 6, 2017

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

This comment has been minimized.

Copy link
Owner Author

amochohan commented Mar 6, 2017

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
You can’t perform that action at this time.