We use the power of Laravel Factories to generate test or dummy data, streamlining development and testing processes by providing a reliable and efficient way to populate our databases with realistic datasets. By using this, developers can speed up their work process in a short time.
You can generate dummy data in Laravel by using Factory Tinker by following step-by-step in below.
Step 1: Run the following command if you have no existing model
php artisan make:factory ModelNameFactory --model=ModelName
This command will create a factory file in the database/factories. Replace ModelName with the name of your model.
Step 2: Define the dummy data in the factory. Open the factory file (ModelNameFactory.php) and edit it.
use Illuminate\Database\Eloquent\Factories\Factory;
class ModelNameFactory extends Factory
{
protected $model = ModelName::class;
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'created_at' => now(),
'updated_at' => now(),
];
}
}
Customize the fields as per your model’s attributes. Laravel uses Faker to generate dummy data. By using faker, you can generate different types of data like Numbers, Lorem text, Person i.e. titles, names, gender etc. Addresses, Phone numbers, Companies, Text, DateTime, Internet i.e. domains, URLs, emails etc. User Agents, Payments i.e. MasterCard, Colour, Files, Images and others.
Step 3: Open Tinker by running the command:
php artisan tinker
Step 4: In the Tinker console, you can use the factory to create dummy data.
** To create single record, use-
ModelName::factory()->create();
** To create multiple record, use-
ModelName::factory()->count(50)->create();
This Will create 50 records with dummy data in your database. After generating the data, you can check your database to see the dummy data.
Step 5: To verify the data, use the command
php artisan make:factory UserFactory --model=User
Step 6: Edit the factory definition from- database\factories\ProductFactory.php
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => bcrypt('password'), // or Hash::make('password')
'created_at' => now(),
'updated_at' => now(),
];
}
We hope this might be helpful for you.