Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3 Call to undefined method Illuminate\Database\Eloquent\Factory::state()

Tags:

php

laravel-5

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.

like image 292
Aaron Dressler Avatar asked Oct 30 '22 18:10

Aaron Dressler


1 Answers

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.

like image 183
Aaron Dressler Avatar answered Nov 09 '22 12:11

Aaron Dressler