I think you need to install the laracasts/TestDummy package.
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!
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
});
Please or to participate in this conversation.