Laravel Global Faker Helper Method

Hello Artisans, today I'll discuss about one of the handy helper method called faker(). Sometimes we may run into a situation where we need to put some dummy data which may come from database or external APIs. Because sometimes we need to put the real-world values for real-world scenarios. And for this reason Laravel recently added a global helper method called faker(). So, no talk let's see what is global faker() helper and how we can use it in our application.

The faker() helper

The faker() helper is singleton. See here for more information about singleton. So, when we use it in our application, a single instance of Faker would be used in our whole application. So, we've already said that it's used across all our applications, that's why we can use it in our blade template also. For more info, we can see the below snippets.

<table width="100%" class="table">
    <thead>
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
    </tr>
    </thead>
    <tbody>
    @for($i=0;$i<10;$i++)
        <tr>
            <td>{{ fake()->name }}</td>
            <td>{{ fake()->unique()->email }}</td>
            <td>{{ fake()->phoneNumber }}</td>
        </tr>
    @endfor
    </tbody>
</table>

Which will produce the below output:

The global faker helper

Not only on blade if we want to use in Database seeders, we can use it like below.

public function run()
{
    DB::table('users')->insert(['name' => fake()->unique()->name()]);
}

Localization using faker() Helper

We can also use it for specific locales like below:

fake('en_AU')->name()

If we don't provide the local name as an argument, it'll take the local en_US by default.

That's it for today. Hope you'll enjoy this tutorial. Thanks for reading.๐Ÿ™‚