How to use Laravel Factory in Database Seeders

By Dillon Smart · · · 1 Comments

Laravel use Factory in Database Seeder

Laravel factories are a great way to add test data to your database in bulk. This saves time, removing the need to write methods to insert data for each column manually. Follow along to learn how to use Laravel Factory in Database Seeders. 

To get started, create a new model. The model we will create will be Post

php artisan make:model Post

Next, we will create a new migration: 

php artisan make:migration create_posts_table 

Open the migration file and add the table schema. In this example, we will give a post a title column which will be a STRING, a description column which will be a VARCHAR, and a content column which will be TEXT. 

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('description');
    $table->text('content');
    $table->timestamps();
});

In Laravel, string is equivalent to VARCHAR with the option to set the length. Text is equivalent to medium text with a maximum of 65,535 bytes. 

Now we have created the migration and the model, we can create the factory and seeder. 

Create a Laravel Factory

To create a Laravel Factory file from the command line, run the following artisan command:

php artisan make:factory PostFactory

Create a Laravel Seeder

To create a Laravel Seeder file from the command line, run the following artisan command:

php artisan make:seeder PostTableSeeder

Add Faker data to a Laravel Seeder

Open the new factory /database/factories/PostFactory and set the model for the factory: 

protected $model = Post::class;

Next, in the definition method, add the following:

return [
    'title' => $this->faker->sentence,
    'description' => $this->faker->paragraph(),
    'content' => $this->faker->text(350),
];

Laravel Factories extend the Factory class, which uses the PHP Faker/Generate class, making the object Faker available to your Factory.

Use your Laravel Factory in Database Seeders

Open the seeder file we generated above. In the run method, add the following:

public function run()
{
    Post::factory()->count(5)->create();
}

The integer used in the count method is used to create the specified number of rows in the table. In this example, we will create 5 records.

Add Seeder file to DatabaseSeeder.php

This step is optional and only applies if you want to run the seeder file when using the –seed flag when running your migrations or db:seed command.

Add the PostTableSeeder file to the run method in the DatabaseSeeder.php file.

public function run()
{
    $this->call([
        PostTableSeeder::class,
    ]);
}

Run Laravel Migrations and Seeders

To run the migrations and seeders at the same time, use:

PHP artisan migrate:fresh --seed

This will refresh the database and run all the seeder files added to the DatabaseSeeder.php file.

Optionally, you can run the single migration file like so:

php artisan migrate --path=/database/migrations/post_migration_file_name.php

Remember to replace “post_migration_file_name” with the name of the migration file.

And to run a single seeder file use:

php artisan db:seed --class=PostTableSeeder

Conclusion

Out of the box, Laravel makes it easy for developers to test their databases by inserting large volumes of fake data. Factories are a great way of generating fake data using the PHP Faker library.

Check out more posts about Laravel

Laravel

1 Comment

Laravel 9: How to Add a New Column to an Existing Table in a Migration - IKnowThatNow

[…] learn how to use Laravel Factories to generate test […]

Was this helpful? Leave a comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Laravel 419 page expired after login [SOLVED]

Updated 1st January 2024

Laravel is the most popular PHP framework, dominating the space since 2014, and the chosen framework by many new PHP developers. Many new developers run into the same errors when first using the framework, the most common being a 419 Page Expired error on a form post.  What is Cross-Site Request Forgery (CSRF)? Cross-site request

Alternative ways of doing the same things in Laravel

Updated 29th March 2022

Laravel is a large framework, with contributions coming from almost 2000 developers worldwide. Over its 10 year journey, there have been additions to the framework to do the same thing, only shorter. In this post, I have highlighted some alternative ways of doing the same things in Laravel. How to get the authenticated users id

Laravel Undefined Constant header_x_forwarded_all after upgrading Laravel version

Updated 1st January 2024

Upgrading to a newer version of Laravel can be exciting, but it can also be nerve racking if you are unfamiliar with the changes in newer version, especially if your upgrading multiple times. Have you received an “Undefined Constant” error in Laravel after upgrading? In this post, I will help you understand the changes under