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 php artisan make:auth command not defined

Updated 11th August 2022

Laravel 6.0 LTS came with a lot of changes to the framework, apart from moving the the new Semantic Versioning, Laravels famous php artisan make:auth command was dropped. php artisan make:auth Before the Laravel make:auth command would create all the Migrations, Models, Controllers and Routes needed to easily setup an authenticatable application in seconds. However,

2022 PHP Usage Statistics

Updated 16th August 2022

PHP: Hypertext Preprocessor is the most popular language used on the web. Around 77.6% of all websites run PHP in some way as of April 2022. PHP has been the driving force behind the growth of the web, but is it slowly dying? Let’s look at some PHP usage statistics. Why is PHP so popular?

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

Updated 1st October 2023

Laravel has a number of features designed to make developing web applications easier and faster. Migrations in Laravel allows us to manage the structure of our databases. In this post, you will learn how to add a new column to an existing table in a migration. Create a new migration file First, we need to