Laravel - How to use faker in PHPUnit test?

once you completed installation of Faker. include autoload file and create instance

$faker = \Faker\Factory::create();
$faker->firstname()
$faker->lastname()

For more information visit


You have to use $this->faker->firstName() not just $faker->firstName()

Update 1

Now when we use WithFaker Trait $this->faker will give us null, to get around this make sure to call $this->setupFaker() first.

e.g.

class SomeFactory
{
    use WithFaker;

    public function __construct()
    {
        $this->setUpFaker();
    }

}

credit @Ebi


For anyone coming here from 2021. We no longer require the addition of

$this->setUpFaker();

You only need to include the trait as described in the accepted answer.