12. Generating Tags, Users and Tagged Posts with a Seeder

At this stage in the blog project, I wanted to create a database seeder which utilises a tag, admin and user seeder. By running a single command, I would be to generate my chosen tags, an admin user and X number of normal authenticated users.


To start with, I created a tag seeder (database/seeders/TagSeeder.php). This seeder populates the tags table with 10 tags, each having a unique name. This can be seen in the screen capture below:



Next, I had to adapt the user factory and include parts of it within the user seeder (database/seeders/UserSeeder.php). The user seeder, makes use of both the user and post factories. The user seeder will create 20 users, each having 3 associated posts. Each of those posts will have between 1 and 6 tags attached to it, reflected in the post_tag table. Because I know that I have 10 tags, I am able to 'shuffle' the possible tags and assign a random number of tags (between 1-6) to each post. As a lengthy function, I made sure that I fully commented the code to make each step easier to understand. The complete user seeder can be found below.



As I'd already made an admin seeder (see the previous post), I can now work on the database seeder (database/seeders/DatabaseSeeder.php). The database seeder is intended to be used to invoke multiple seeders - meaning that a single command can be run, instead of running one command for each seeder.

Before running the database seeder, I ran the following command in the terminal window:
php artisan migrate:fresh
This provided me with empty database tables, ready to be populated.

The database seeder first populates the tags table by running the tag seeder. This was necessary, as the user seeder relies upon 10 tags to be existing already. Next, the admin seeder is run - resulting in a new admin user being created. Since the databases had been freshly migrated, this placed the admin user at the top of the users table (with an id of 1). Finally, the user seeder is run, creating 20 users (with ids 2-21). Each of these users had 3 posts each, so 60 new posts were generated in total. As mentioned, each of these new posts would be associated with 1 to 6 tags.



To run the database seeder, I ran the following command:
php artisan db:seed --class=DatabaseSeeder
The --class flag relates to the seeder I want to run. The screen captures below show the results of running the database seeder as seen in Table Plus.

Tags table:



Tags table structure:



Users table:
(Note: the user with an id of 22, was created by myself after having run the database seeder.)


Users table structure:



Posts table:


Posts table structure:



Post_Tag table:

Post_Tag table structure:



Comments