Laravel 10 - How to Generate Fake Data with Laravel's Faker Library
Hello Artisan, today I'll show you how to generate fake data using Faker. Laravel's Faker library provides a simple way to generate fake data for your application. It can be used to generate fake names, addresses, phone numbers, dates, and much more. So, let's see how we can easily create a set of fake data in our application.
Note: Tested on Laravel 10.8
- Usage of Faker Library
Faker can be useful for testing and development, or for creating sample data to show to clients or stakeholders. Let's see how we can easily create fake data. Faker gives us multiple helpful methods for generating fake data. Let's see the available method first.
- name(): Generates a random name.
- firstName(): Generates a random first name.
- lastName(): Generates a random last name.
- email(): Generates a random email address.
- password(): Generates a random password.
- phoneNumber(): Generates a random phone number.
- address(): Generates a random address.
- city(): Generates a random city name.
- state(): Generates a random state name.
- postcode(): Generates a random postal code.
- country(): Generates a random country name.
- sentence(): Generates a random sentence.
- paragraph(): Generates a random paragraph.
- text(): Generates a random text.
- randomElement($array): Returns a random element from the given array.
- dateTime($max = 'now', $timezone = null): Generates a random date and time.
- numberBetween($min = 0, $max = 2147483647): Generates a random number between the given range.
- boolean(): Generates a random boolean value.
Let's see how we can use these in our real life
So as we see in the above example first we'll initialize a $object of the factory class and then we use a method called name() to generate a fake name. We can also get multiple names or countries as well. Let's look at the below example
Which can give you a list of countries like the above image. Even we can use it to generate multiple rows for a table. For this, first, we've to create a faker first using the following command.
For example, we'll use the default UserFactory provided by Laravel. Just fire the below command in your terminal
Add if you see in your table, you can see you've created 10 users in the users table.
So thus it'll help for creating dummy records and of course, it'll help us in developments as well.
Thank you for being so supportive!
0 Comments
CAN FEEDBACK
Emoji