Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mrs_Beginner's avatar

PHP Notice: Undefined variable: factory in MyWebsite/config/database/factories/UserFactory.php

hi today i was editing my project in search.balde.php and suddenly after i run my project i faced below error:

PHP Notice:  Undefined variable: factory in MyWebsite/config/database/factories/UserFactory.php on line 17

my UserFactory.php code is like below


<?php

use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => 'y$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];
});

and $factory->define(App\User::class, function (Faker $faker) { is line 17.

i am pretty sure that i didn't touched UserFactory.php today. i restored my search.blade.php to when website was fine but this error was still there. i am completely mixed up now an this error makes me crazy. can any one help me on this issue?

0 likes
1 reply
tisuchi's avatar

@mrs_beginner

I am not sure, but there is a way to solve this issue is by adding the following line on top of the class.

/** @var \Illuminate\Database\Eloquent\Factory $factory */

So, it will be like this-

<?php

use Faker\Generator as Faker;
/** @var \Illuminate\Database\Eloquent\Factory $factory */

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => 'y$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];
});

Ref: https://stackoverflow.com/questions/57847479/factory-undefined-variable

2 likes

Please or to participate in this conversation.