The global faker helper in Laravel 9.x — Amit Merchant — A blog on PHP, JavaScript, and more


How many times does this happen to you that when you’re building UIs, you add placeholders (Lorem Ipsum, “John Doe”etc ..) to the places where it needs data from database or external APIs?

I’m pretty sure you have come across this scenario one time or another. While, it’s perfectly okay to use these placeholder texts, sometimes, it’s important to test things using “Real-world” values ​​for real-world scenarios.

To cope with this, a PR in Laravel recently introduced a handy fake() helper that lets you do just that!

The fake() helper

This PR by Tim MacDonald adds a global fake() helper. You can make use of it to have placeholder values ​​across the entire application. Even in your blade templates as well!

This helper is a singleton. Meaning that when you use it in your application, a single instance of Faker would be used all across your application.

Quoting the PR, here’s what this would look like in a Blade template.

@for($i = 0; $i < 10; $i++)
        <dd> fake()->name() </dd>

        <dd> fake()->phoneNumber() </dd>

As you can tell, it’s pretty convenient to use fake values ​​that Faker supports without importing anything. It just works!

You can use it to have unique values ​​across various things as well.

return [
    'email' => fake()->unique()->email(),

In Database seeders…

function run()

    DB::table('users')->insert(['name' => fake()->unique()->name()]);

Using different locales

You can also pass in a locale to the fake() helper if you want locale-specific values ​​like so.

fake('en_AU')->name() // en_AU

The default locale is en_US if app.faker_locale isn’t set in the config.

Also, the app will have a separate singleton when you pass in a locale to the faker() helper.



Please enter your comment!
Please enter your name here