Now that we have discussed creating factories, we can look at how to use these factories to seed our database with test data.
Why Do They Exist and When Should You Use It?
Seeders allow you to generate a lot of test data very quickly. Instead of manually creating a large amount of test data you can leverage your factories to quickly spin up tens, hundreds, or even thousands of test rows so you can test and demo your application.
Let’s Build a Seeder
In this section we’re going to build a seeder using the
ProjectFactory we created in our last post. To do this we’re going to use
This will create a class in the file “database/seeds/ProjectTableSeeder.php” that looks like the following.
We’re not going to put anything into this just yet because there’s still some setup we need to do. First, open “database/seeds/DatabaseSeeder.php”. It will look like the following.
We’re going to change it so it knows about our
This will tell Laravel to look for the
ProjectTableSeeder class when we want to seed our database. This is done by using the
db:seed command. If we run this command now we’ll receive the following error message.
Illuminate\Contracts\Container\BindingResolutionException : Target class [ProjectsTableSeeder] does not exist.
In order to fix this we need to run
composer dump-autoload so it can detect the new class. After composer runs we can run
db:seed again and get the following results.
Because we didn’t actually put anything in our seeder this didn’t do anything so let’s revisit our
ProjectTableSeeder and update it to create 100
Projects for us.
Now we can run
db:seed and the command will create the
See how it took 0.41 seconds instead of 0. That’s artisan creating 100
We can also create a
TasksTableSeeder and add it to
DatabaseSeeder. We could continue to add
$this->call() to the
run() function but we can also change the call to the
call() function to be an array of all the classes we need.
db:seed will also create the
Tasks for us.
Seeding a Single Table
In cases where we need to create a bunch of data for a specific module for testing/demo purposes,
db:seed has a
--class parameter that will allow you to run a single seeder.
Refresh and Seed
If you ever hit a point where you need to reset your database but also have test data,
migrate:refresh also has a
--seed parameter so you can refresh you database and seed it with new data at the same time.
Hopefully this has been as helpful to you as it has to me. Check back soon for more artisan commands.
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.