Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The global faker helper in Laravel 9.x

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++)
        <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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), 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-digest 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.

Like this article? Consider leaving a


👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.