Created
March 6, 2017 09:53
-
-
Save amochohan/aa3eaf01a03a66fe6424bd4f9dcd8539 to your computer and use it in GitHub Desktop.
Model factories - making relationships
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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. |
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
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.