Model Factories

Introduction:

Laravel comes with a feature called Model Factories that are designed to allow you to quickly build out “fake” models.

These have several use cases so that you can use them to build out “dummy” models which can be used for both seed data and testing.

Normally we don’t need to create a new one, we can use the default database/factories/UserFactory.php file for multiple factories.

Open database/factories/UserFactory.php file and you will see an UserFactory is already defined:

$factory->define(App\User::class, function (Faker\Generator $faker) {

return [

'name' => $faker->name,

'email' => $faker->email,

'password' => bcrypt(str_random(10)),

'remember_token' => str_random(10),

];

});

$factory->define(App\Post::class, function (Faker\Generator $faker) {

return [

'subject' => $faker->sentence(5),

'description' => $faker->text(),

];

});

We are defining the “App\User::class” model as the first parameter and then a callback that defines the data that goes in the columns. This callback also injects Faker which is a PHP library that generates fake data. Faker is powerful and can be used for a number of different field types.

And as we can see the another factory is for the Post model in the same file. Hence we can make multiple factories. 

If we create a new factory for a model then we need to write as follows.

Now, let’s create a new factory for our Post Model:

php artisan make:factory PostFactory

Here is the complete code for the factory:

$factory->define(App\Issues::class, function (Faker\Generator $faker) {

return [

'subject' => $faker->sentence(5),

'description' => $faker->text(),

];

});

The --model option may be used to indicate the name of the model for which the factory is created. This option will pre-fill the generated factory file with the given model:

php artisan make:factory PostFactory --model=Post

 

  • 249
  • 308
  • By Bablu Ahmed
  • Posted 1 year ago