TonsOfLaz's avatar

5.1 - Model Factory - creating object within a factory

Hi,

I have been trying to get a basic example working where I create a model inside my Model Factory, but I am getting an error that the variable factory is not defined. I am using a snippet directly from Jeffrey Way's description of how to do it a comment on the main Model Factories video.

Here is my code, in factories/ModelFactory (the 5.1 default location):

$factory->define('App\NewsArticle', function($faker) {
    return [
        'active' => $faker->randomNumber(),
        'date' => $faker->dateTime(),
        'url' => $faker->url,
        'title' => $faker->word,
        'source' => $faker->word,
        'intro' => $faker->text(),
        'category_id' => $factory->create('App\Category')->id,
        
    ];
});

The error is Undefined variable: factory, and it is because of the last line in the factory definition, with the Category object.

Does anyone see the error here, or have you been able to make this work? I feel like it must be something obvious, but I don't know why it isn't recognising the $factory variable.

Thanks in advance!

0 likes
6 replies
bobbybouwmann's avatar

You need to create a directory called factories and you can place a file in it called all.php and fill the file with this

<?php

$factory('App\NewsArticle', function($faker) {
    // Your stuff here
});

Now you can call it in your code

$newsArticle = TestDummy::create('App\NewsArticle');
1 like
TonsOfLaz's avatar

Thanks for the replies, but I should clarify:

@usman I am using Laravel 5.1, so I don't think I need to include the Laracasts/TestDummy package.

@bobbybouwmann The code I posted is in the factories/ModelFactory.php class, which is the default alternative to the factors/all.php in 5.1.

The issue I am having is with this line: 'category_id' => $factory->create('App\Category')->id,

It doesn't recognize the $factory variable.

bobbybouwmann's avatar
Level 88

Oow you use the beta, could have known that!

Try this

// Notice the use statement!
$factory->define('App\NewsArticle', function($faker) use ($factory) {
    // Your stuff here
});
1 like
clausche@gmail.com's avatar

//'category_id' => $factory->create('App\Category')->id, category_id' => function(){ return $factory->create('App\Category')->create()->id // or make() }

Please or to participate in this conversation.