Laravel Factories, Seeder
Today's tutorial, you will learn how to create dummy data in database using Laravel Factory and Seed the database by using Database Seeder.
Generate model factory
Firstly, you need to generate model factory. To generate model factory, run below command in your terminal:
1
php artisan make:factory UserFactory --model=User
1 | php artisan make:factory UserFactory --model=User |
This will create a new file called UserFactory.php in database/factories folder.
Now we need to add fake data for each column in our model. For example, if we have a column called name, we need to add fake data for that column in our factory. Paste the below code in our factory file:
1 | <?php |
Create User Seeder
Now, we need to create a seeder For UserTable by running command below:
1
php artisan make:seed UserTableSeeder
1 | php artisan make:seed UserTableSeeder |
This will create a new file called UserTableSeeder.php in database/seeders folder.
Next Update the run function of seeder file. Paste the below code in the run function:
1 | <?php |
Seed the Data
Now Run the command below to seed the data:
1
php artisan db:seed --class=UserTableSeeder
1 | php artisan db:seed --class=UserTableSeeder |
Conclusion
In this tutorial, we learned how to create dummy data in database using Laravel Factory. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.
Happy Coding
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.
Comments
GitalkDisqus