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.

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

How to use Microsoft Graph API with Laravel

Updated 1st January 2024

Microsoft Graph is a gateway to data and intelligence within Microsoft 365. Microsoft Graph is great to build apps for organizations and consumers using the vast amount of data stored in Microsoft 365. In this post, we are going to integrate with Microsoft Graph API in Laravel to get all users assigned to your tenant.

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,