Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The global faker helper in Laravel 9.x

July 5, 2022 ·

How many times does this happens 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++)
    <dl>
        <dt>Name</dt>
        <dd>{{ fake()->name() }}</dd>

        <dt>Phone</dt>
        <dd>{{ fake()->phoneNumber() }}</dd>
    </dl>
@endfor

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.

Learn the fundamentals of PHP 8 (includes 8.1 and 8.2), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?