As we know, testing is a very important part of any web development project. Often we may require adding hundreds, or maybe thousands of record to our users table. Just think about if you require pagination then you have to include some records for testing. So what will you do at that moment? Will you manually add thousands of records? What do you do? If you add manually thousands of records it may require much time.
Moreover, Laravel has a tinker that provides to create dummy records for your model table and by default provide a User model factory. You can see how to create records using the factory below:
Generate Dummy Users
php artisan tinker
User::factory()->count(5)->create()
This by default created a factory of Laravel. You can also see that at the following URL: `database/factories/UserFactory.php`.
Create Custom Factory
But when you need to create dummy records for your products, items, or admin table, then you have to create a new factory using the tinker command. Here, I will give you a simple example of creating a product factory, and you will understand how it works. So let’s create a Product Model as shown below:
app\Models\Product.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; protected $fillable = [ 'name', 'slug', 'detail' ]; }
Now let’s create our custom factory using the below command:
php artisan make:factory ProductFactory --model=Product
Read More Blogs
Laravel 12 Send Email using Queue Example
Laravel 12 Image Intervention Tutorial With Example
Laravel 12 New Starter Kits | TutorialDev
Now they created a new Factory class for products, and you can add the code below:
database\factories\ProductFactory.php
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; use App\Models\Product; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory */ class ProductFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Product::class; /** * Define the model's default state. * * @return array */ public function definition(): array { return [ 'name' => $this->faker->name, 'slug' => Str::slug($this->faker->name), 'detail' => $this->faker->text, ]; } }
Using Faker, you can generate the following data types:
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
uuid
Barcodes
If you see above, you can simply use data types. Now we are going to create 500 records of the products table by following command:
Generate Dummy Product:
php artisan tinker
Product::factory()->count(500)->create()
So I hope you’ve created your 500 dummy records in the products table.