DEV Community

Arif Iqbal
Arif Iqbal

Posted on • Updated on

Database Seeding in Laravel

Ep#27@Laracasts: Database Seeding Saves Time

This post is a part of the Week X of 100DaysOfCode Laravel Challenge series. We are building the Blog project while following the Laravel 8 from Scratch series on Laracasts with the 100DaysOfCode challenge.

In development we often run the php artisan migrate:fresh command to refresh our database and to apply any changes made to the schema. This command deletes all the data from our database. It is very cumbersome to write the data back to the database again and again manually. Laravel has a very convenient solution for this problem in the form of Database seeders.

Database seeders are PHP classes responsible for generating records for your database tables. These seeder classes are stored in the databases/seeders directory. This directory by default has a seeder class for you in the file DatabaseSeeder.php. If we inspect this class, it has a method run() inside which is the code

// \App\Models\User::factory(10)->create();
Enter fullscreen mode Exit fullscreen mode

This code has the method factory() which we are not yet quite familiar with. But sounds like this code generates 10 records for the users table. The question is how to run this code? Laravel has the command php artisan db:seed for this.

First, uncomment the line in the seeder class and then run the php artisan db:seed command. You will see users table has now 10 records. If you run the command again, 10 more records will be added without deleting the previous records. To prevent this, you can empty your table before writing new data to it. Write the this line User::truncate(); before the code that creates users.

\App\Models\User::truncate();
\App\Models\User::factory(10)->create();
Enter fullscreen mode Exit fullscreen mode

You can seed your database immediately after refreshing it by adding the --seed option to the end of of the refresh command.

php artisan migrate:fresh --seed
Enter fullscreen mode Exit fullscreen mode

Note: This post will be updated soon with more details about the Blog Project.

Discussion (0)