PASSWORD RESET

Your destination for complete Tech news

How to create fake data using faker and factory in Laravel?

1.17K 0
< 1 min read

To create fake data using Faker and factory in Laravel, you’ll need to do the following:

Install the Faker library: You can install the Faker library using Composer by running the following command

composer require fzaninotto/faker

Create a model factory: A model factory is a class that generates fake data for a given model. You can create a model factory by running the make:factory Artisan command and specifying the name of your model. For example:

php artisan make:factory UserFactory

This will create a UserFactory class in the database/factories directory.

Define the fake data for your model: In your model factory class, you can use the Faker library to define the fake data that should be generated for your model. For example

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

This model factory generates fake data for a User model, including a name, email address, password, and remember token.

Create fake data using the factory: Once you’ve defined your model factory, you can use it to create fake data by calling the create method on the factory and specifying the number of records you want to create. For example:

factory(App\User::class, 10)->create();

This will create 10 fake user records in your database.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.