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 – Specified key was too long Error

Updated 18th May 2021

With Laravel 5.4, some users may be hit with the Laravel Specified key was too long Error when migrating the database. This is because in the latest Laravel update, the developers made changes to the default database charset, making it utf8mb4. If your using MySQL 5.7.7 or higher, you won’t encounter this issue, however older versions of MySQL

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

How to access Laravel env variables in Vue.js | Laravel MIX

Updated 16th August 2022

Using Laravel and Vue together is a common approach as it allows the MVC framework to handle the logic, and an application-like user interface for the frontend. Learn how to use Laravel environment variables in Vue.js. MIX Environment Varaibles Vue js files are compiled by Laravel Mix. To have Mix compile your environment variables from