5

A new factory in laravel looks like this;

<?php

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

use App\Model;
use Faker\Generator 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 \Illuminate\Database\Eloquent\Factory object

Ramon Bakker
  • 1,075
  • 11
  • 24

1 Answers1

10

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: \Illuminate\Database\Eloquent\Factory::load

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

/** @var \Illuminate\Database\Eloquent\Factory $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.

lbrandao
  • 4,144
  • 4
  • 35
  • 43
  • When and how does this load-function get called? – Plumpie Aug 06 '20 at 12:56
  • Still don't get it, where does factory() come from then? I looked at the list of service providers in app.php, only DatabaseServiceProvider gets loaded there, which doesn't register a $factory as far as I can see – Plumpie Aug 10 '20 at 09:25
  • 1
    The factory() helper function is defined in the helpers.php file. There is a link to it in the answer. – lbrandao Aug 10 '20 at 13:44