Let's suppose we create a website, but can we test our site without having data? The model factory in Laravel tests the website by adding mock data to the database—preventing the hassle of adding testing data manually.
The model factory can generate many random records in the database. There are two steps to generate the mock data using the model factory in Laravel as given below:
Define a model factory
Create a dummy data
Note: We are using Laravel 9.
We can define the factory through CLI by using the following command:
php artisan make:factory UserFactory
factory
: This represents defining a new factory.
UserFactory
: This represents the name of a factory.
Now, let's navigate to the UserFactory
file in the project. Here, we have a definition
method where we can define the desired columns for a user table as given below:
class UserFactory extends Factory {public function definition(){return['name' => fake()->name(),'email' => fake()->unique()->safeEmail(),'number'=> fake()->phoneNumber(),];}}
We defined the columns for our user table. Now, let's move to the DatabaseSeeder.php
file, which is located in the seeder
folder. Here, we have the run()
method where we can create records.
For example, creating the dummy data for 100
users is given below.
public function run(){User::factory(100)->create();}
Now, run the following command on CLI:
php artisan db:seed
After running the above command on CLI, the user table is filled with 100 records.
Free Resources