Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

murilo's avatar
Level 10

faker in laravel for testing , gerate the faker data but dont store in database

hello , I need a faker to testing with Pest , the store Method . I need something like that -

$data = $factory->define(UserAdmin::class, function (Faker $faker) {
        return [
            'name' => $faker->name,
            'email' => $faker->email,
        ];
    });

    postJson(config('app.url').'/api/admin/users/store', $data )->json();

I saw that in laravel 7 , it has this method . define . but in laravel 10 , I think that does not has .

I tryed as well -

 $factory = new Faker();
    $data = $factory->define(UserAdmin::class, function (Faker $faker) {
        return [
            'name' => $faker->name,
            'email' => $faker->email,
        ];
    });
    dd($data);

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

In Laravel 10, the approach to using factories has changed compared to Laravel 7. The define method is no longer used. Instead, Laravel uses class-based factories. Here's how you can achieve what you're trying to do using the new factory system in Laravel 10.

First, ensure you have a factory for your UserAdmin model. You can generate a factory using Artisan:

php artisan make:factory UserAdminFactory --model=UserAdmin

Then, define the factory structure in database/factories/UserAdminFactory.php:

namespace Database\Factories;

use App\Models\UserAdmin;
use Illuminate\Database\Eloquent\Factories\Factory;
use Faker\Generator as Faker;

class UserAdminFactory extends Factory
{
    protected $model = UserAdmin::class;

    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->safeEmail,
        ];
    }
}

Now, in your test, you can use this factory to create an array of attributes without persisting them to the database:

use App\Models\UserAdmin;

test('example test', function () {
    $data = UserAdmin::factory()->make()->toArray();

    $response = $this->postJson('/api/admin/users/store', $data);

    $response->assertStatus(200);
});

In this example:

  • UserAdmin::factory()->make() creates a new UserAdmin instance without saving it to the database.
  • ->toArray() converts the model instance to an array of attributes, which you can then use to send as JSON payload in your test request.

This approach should work seamlessly with Laravel 10 and allows you to test your endpoints without persisting test data to your database.

Please or to participate in this conversation.