Factory and Database Seeder


Seeder

class DatabaseSeeder extends Seeder {
    public function run(): void {
        [ModelName]::factory(10)->create(); 
        // it will the factory template 10 times
    }
}

Model

prepare the model to be used by the factory by adding fillable properties

protected $fillable = ['title','description','long_description'];

Factory

create a factory and link to the model using this code:

php artisan make:factory TaskFactory -model=Task

modify the definition() method with FakerFaker1. faker (lowercase) * In Laravel, faker is often used as a property in factories or test cases, and it provides access to an instance of the Faker class. * Laravel automatically resolves faker for you in many cases, such as in factory definitions or PHPUnit tests. * Example in a factory: 'name' => $this->faker->name, * It is a shorthand for using the Faker library in Laravel. 2. Faker (uppercase) * Faker is the actual class provided by the Faker library. * It's a PHP library used to ge in the factory file:

// example: TaskFactory.php
public function definition(): array {
	return [
		'title' => $this->faker->sentence,
		'description' => $this->faker->paragraph,
		'long_description' => $this->faker->paragraph(7, true),
		'completed' => $this->faker->boolean,
	];
}
// example: BookFactory.php
public function definition(): array
    {
        return [
            'title' => fake()->sentence(3),
            'author' => fake()->name,
            'created_at' => fake()->dateTimeBetween('-2 years'),
            'updated_at' => fake()->dateTimeBetween('created_at','now')
        ];
    }

Status: #idea
Tags: web-programmingWeb Programming (Laravel)Mid Exam Materials Final Exam Materials Status: #MOC Tags:


References