We need test data to test our program. We need to test each and every test cases. Laravel gives a very good feature called Laravel Factory and Seeder to create your test data quickly. So you do not have to spend hours to manually create each test data to satisfy program logic.
In this topic, we will show how you can use Laravel Factory and Seeder to create fake or dummy data in MySQL database. When you develop an application, you need proper test data to test it. Factory and Seeder are Laravel Libraries using which you can create test data easily.
We will use a custom table for whcih we will create test data using Laravel factory. Create a factory on that table and then update
DatabaseSeeder.php to call the factory. Then run database seeder. Let us use below Steps to complete creating test data.
- Create a Laravel 10 project
- Create a MySQL database migration
- Create a Laravel factory file for the newly created table
- Verify data in the table
1. Create a Laravel 10 project
Let us create a project in laravel 10. Make sure you have composer and PHP installed in your system. I have given the project name as lara_seeder.
This will create a folder named "lara_seeder" under the folder where you run the above command.
2. Create a MySQL database migration
.env file for database details. I am using MySQL database named 'lara_demo', so I updated the file as below:
We will create a new table called "applications" for all applicants who registered. You can use existing table like "users" to populate test data in it also. Then you do not need to create new table, you can directly create the factory file.
Let us create a Laravel migration file for this table. Go to your project folder and run below command for migration from VS code terminal.
Above command will create the migration file name
<yyyy_mm_dd_xxxxxx>_create_applications_table.php under database/migrations folder and Application model will be created in app/Models folder.
Update migration file
Let us update the above migration file as below:
Let us now run Laravel migration to create the default Laravel tables as well as our custom "applications" table. Run below command from project folder to create the tables.
After running migration see the structure of 'applications' table.
3. Create a Laravel factory file for the newly created table
Let us create a factory for Application model as below:
Update ApplicationFactory as below:
Now, update run() method of
DatabaseSeeder.php under database/seeders folder to call the factory we created. I have used 100 here to create 100 rows in applications table.
5. Run db:seed
Now, run Laravel database seeder to create the rows:
6. Verify data in the table
You can see there are 100 rows created in applications table.
We are done with test data creation. Hope it will be useful for you.