Skip to content
Advertisement

How does a Laravel factory gets the $factory variable defined?

A new factory in laravel looks like this;

<?php

/* @var $factory IlluminateDatabaseEloquentFactory */

use AppModel;
use FakerGenerator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    return [
        //
    ];
});

The variabele $factory does’nt get defined in this file. How and where does this variabele get defined? A dd($factory) results as expected in an IlluminateDatabaseEloquentFactory object

Advertisement

Answer

The variable $factory is not defined in the file itself. Only when this file is processed by Laravel, by including it during the loading process, is that $factory will reference the Factory object.

This is where factory files get loaded: IlluminateDatabaseEloquentFactory::load

Note the docblock at the beginning of the factory file, it’s there to help your IDE with auto-completion:

/** @var IlluminateDatabaseEloquentFactory $factory */

Now you might wonder where Factory::load() first gets called. It gets called when the Factory is first instantiated by the DI container, once you use the factory() helper for instance.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement