Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 839
Ramon Bakker Avatar asked Jun 05 '20 17:06

Ramon Bakker


Video Answer


1 Answers

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.

like image 159
fromvega Avatar answered Oct 09 '22 05:10

fromvega