Factory – Laravel

To create a factory use make:factory

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

php artisan make:factory PostFactory --model=Post

Writing Factories inside created PostFactory file

All column data are written inside the return[ ].  $faker instance is used to use the various properties and assign to the column attributes.

<?php

use Faker\Generator as Faker;

$factory->define(App\Film::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence(5),
        'description' => $faker->realText(rand(80, 600)),
        'release_date'  => $faker->date(),
        'rating' => rand(1,5),
        'genre_id' => function () {
            // Get random genre id
            return App\Genre::inRandomOrder()->first()->id;
        },
        'photo'  => 'https://via.placeholder.com/350x150',
        'slug'   => str_replace('--', '-', strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', trim($faker->sentence(5))))),
    ];
});

Run method inside => DatabaseSeeder.php

After writing down the code for factory, the next step is to call factory method with number of data we need as shown on below. Here 15 number is written

factory(App\Permission::class,15)->create();

Run Artisan Comman => Create Faker Data

It will execute all the code written inside DatabaseSeeder.php

  • php artisan db:Seed

Example:

Factory

Here 5 factory file is created and used

UserFactory.php

InfoFactory.php

ArticleFactory.php

CategoryFactory.php

PermissionFactory.php

UserFactory.php

$factory->define(App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});

InfoFactory.php

$factory->define(App\Info::class, function (Faker $faker) {
return [

'address' => $faker->address,
'mobile' => $faker->randomNumber(),
'mobile_verified_at' => now(),
'role' => $faker->numberBetween(1,5),
];
});

ArticleFactory.php

$factory->define(App\Article::class, function (Faker $faker) {
return [
'title' => $faker->sentence(2,4),
'content' => $faker->paragraphs(rand(5,10),true),
'slug' => $faker->slug(),
'category_id' => function(){
// Get Random Category ID
return App\Category::inRandomOrder()->first()->id;
}


];
});

 

CategoryFactory.php

$factory->define(App\Category::class, function (Faker $faker) {
return [
'name'=> $faker->word,
];
});

PermissionFactory.php

$factory->define(App\Permission::class, function (Faker $faker) {
return [
'user_id' => function () {
// Get random genre id
return App\User::inRandomOrder()->first()->id;
},

'category_id' => function () {
// Get random genre id
return App\Category::inRandomOrder()->first()->id;
},
];
});

DatabaseSeeder.php

public function run()
{

DB::statement('SET FOREIGN_KEY_CHECKS=0');
DB::table('users')->truncate();
DB::table('infos')->truncate();
DB::table('articles')->truncate();

factory(App\Category::class,5)->create();

factory(App\User::class,5)->create()->each(function($user){

$user->info()->save(factory(App\Info::class)->make());

$count=0;
$total=rand(0,5);
while($total>=$count)
{
$user->article()->save(factory(App\Article::class)->make());
$count++;
}

});


factory(App\Permission::class,15)->create();


}

 

Artisan Factory Run Command

php artisan db:seed

Leave a Reply

Your email address will not be published. Required fields are marked *