8. Making Factories to Generate Users and Posts

In Laravel, factories can be used to generate data for database tables, which is very useful while testing an application that is in development. It can also be used to prepare an app for production, where certain tables may require data prior to launch (such as tables that do not store user input).

A user factory (database/factories/UserFactory.php) is already included in the code due to the scaffolding, however, I need to adapt it to match my requirements. The screen capture below shows various values being faked to create valid database entries. The configure() method contains a function which interacts with the post factory (database/factories/PostFactory.php). After a user is created, a new post is also created using the new user's id as the post's user_id foreign key.


To generate a post factory, I run the following command:

php artisan make:factory PostFactory

The post factory (database/factories/PostFactory.php) creates faked data for a new post. As mentioned above, this factory is run automatically when a new user is created using the user factory - i.e. two birds with one stone.


I could test this approach in tinker by running the following command:

User::factory()->count(2)->create();

This results in two new users and two new posts being created, where each post is associated with one user via the foreign key relationship. Alternatively, I could edit the post factory (on line 40) to:

\App\Models\Post::factory()->count(3)->create(['user_id' => $user->id]);

This would result in 3 new articles being created every time a single new user is generated.

Comments