Laravel provides a convenient way to create dummy data using the built-in factory feature. You can use factories to generate random data for your database tables. These dummy data can be used for testing purposes. As we know while developing any application, we need to do the unit test. But, sometimes, we don’t have much data to test every scenario. However, by using a factory in Laravel 10, you can create dummy data in the database. This will make the testing easier with the dummy data. It will make it easier to populate your database with test data. Factory in Laravel 10 can create N number of test data. The factory uses the faker class to generate dummy test data. There are different data types available like name, email, phone number, address, etc.
In this post, we will be implementing an example to create dummy data using a factory in Laravel 10. However, the factory in Laravel will be executed using Tinker. Let’s know about Tinker first before moving to the example.
What is Tinker in Laravel
Tinker is a REPL (Read-Eval-Print Loop) tool included with Laravel. It allows you to interact with your application’s code and data through a console. It provides an easy way to test and debug your application without creating complex testing scenarios.
Now, let’s understand through an example in this post.
How to Create a Seeder in Laravel 10 For Seeding Test Data
Prerequisites
We are going to implement an example of a factory in Laravel 10 to create fake data. The example will consist of a Laravel 10 application. Hence, for working with a Laravel 10 application, you need the below requirements.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Step 1 – Create a Project to Implement Factory in Laravel 10
In the very first step, you need to create a Laravel 10 application. However, if you already have a project setup then you can skip this step.
composer create-project --prefer-dist laravel/laravel my-app
Once you are done with the Laravel 10 application, you will require a database connection.
Step 2 – Create and Configure a Database
You need to create a database first. After that navigate to the project folder and inside the .env file, add the DB credentials as shown below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE={{ DATABASE_NAME }}
DB_USERNAME={{ DATABASE_USERNAME }}
DB_PASSWORD={{ DATABASE_PASSWORD }}
Now, we will be moving to the next step.
How to Create Authentication Using Breeze Auth in Laravel 10
Step 3 – Create a Model and Migration in Laravel 10
You need a migration and a model. Inside the migration, we will be adding the schema of the table for which we will be inserting dummy data.
php artisan make:model Employee -m
If you want to create a controller using the same command then you have to pass one additional flag. Take a look at the below command.
php artisan make:model Employee -mc
After creating these files, let’s move to the next step of adding schema.
Step 4 – Add Schema in the Migration File
We have the migration, model, and controller respectively for the employee. Hence, firstly, you have to add the schema in the migration file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('gender')->nullable();
$table->string('email')->nullable();
$table->string('phone_number')->nullable();
$table->string('password')->nullable();
$table->string('address')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('employees');
}
};
I have added some basic fields here in the migration. You can add more fields as per your requirement.
Next, you need to migrate the database using the below command.
php artisan migrate
In the next step, you need to do a mass assignment in the model in order to save dummy data using the factory in Laravel 10.
How to Create Auth Scaffolding Using React JS in Laravel 10
Step 5 – Add Fillable Property to Use Factory in Laravel 10
You need to move to the model and then add the mass assignment as shown below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $fillable = [
'first_name',
'last_name',
'gender',
'email',
'phone_number',
'password' .
'address'
];
}
After adding the fillable property, you have to create a factory class respective to this model and migration.
Step 6 – Create a Factory in Laravel 10
In order to create a factory class, you need to hit the below command.
php artisan make:factory EmployeeFactory --model=Employee
This command needs a model from which it will be linked. That means, the factory will insert the data through the model. Hence, you need to specify that. In our case, we have the Employee model. So, we have added this.
After creating the factory, you need to add the definition of the columns for which you will be adding dummy data.
Step 7 – Add Definition in Factory in Laravel 10
Inside the factory class, you need to add the definition of the columns as shown below.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Employee>
*/
class EmployeeFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'first_name' => fake()->firstName(),
'last_name' => fake()->lastName(),
'gender' => fake()->randomElement(['Male', 'Female']),
'email' => fake()->unique()->safeEmail(),
'phone_number' => $this->faker->phoneNumber(),
'password' => bcrypt('password'),
'address' => fake()->address(),
];
}
}
As per the columns added in the schema, I have added the definition. Next, you need to trigger autoload so that the tinker and other dependencies will be ready to be executed.
composer dump-autoload
In the next step, you need to run the factory method.
How to Create Auth Scaffolding Using Vue JS in Laravel 10
Step 8 – Run Factory Method Using Tinker
Lastly, you need to execute the factory create method in order to create records. Here, you have to specify the number of records.
For example, if you want to create 100 records of Employees then you need to specify as added below.
php artisan tinker
Employee::factory()->count(100)->create()
The command will initiate the factory class to create dummy records.
If you will check into the database table, then you will find the records are inserted.
The factory class provides different sets of values based on the data types.
Final Words
We have implemented functionality to save dummy data using Factory in Laravel 10. The factory provides fake() method to have different data types. These data types will contain different sets of data. The factory class method can be executed using the Tinker. We have seen how to run the factory create method using Tinker in the console. That’s it for this post, I hope, this post will be interactive and helpful for you.
Leave a Reply