I'm trying to define a few different variations of a User model for testing, using Laravels ModelFactory as documented here
$factory->define(App\User::class, function(\Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'remember_token' => str_random(10),
'phone' => $faker->phoneNumber,
];
});
$factory->state(App\User::class, 'admin', function (Faker\Generator $faker) {
return [
'groups' => function(App\User $u) {
return App\Models\Group::where('level', '<=', 5)->get()->toArray();
}
];
});
And then I create a User model:
$user = factory(User::class)->states('admin')->make();
But phpunit seems to exit out of the test without complaining. In the PHP logs, I see:
Call to undefined method Illuminate\Database\Eloquent\Factory::state()
There isn't very much documentation on the state() method in Laravel docs, and I've searched and experimented for hours with no progress to show for it.
As a sidenote: the groups
attribute is referring to a Many relationship. However, this Exception is thrown regardless of which model I am creating, even simple models.
After digging around in the Illuminate\Database\Eloquent\Factory and FactoryBuilder classes, I discovered that the state() and states() methods were both missing, compared to the latest Laravel branch on github. After running composer update, it updated me to Laravel Framework v5.3.18, and now the ModelFactory states work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With