Add Faker to Laravel for Dummy Data

When it comes to generating dummy data for PHP applications, Faker is the most well-known library. It can be used to generate any type of data, from a number, human name, or city, to a credit card number, username, and password.

I wrote a post about using Faker in CodeIgniter. There are some steps to follow to use Faker. However, we don’t need those steps applied to Laravel, the framework (v5.0+) already has Faker built-in.

To test some functions of the Faker library you just need to create a Faker object and return data from some methods from your web routes file .

Add library

use Faker\Factory as Faker;

Test function in web route

	$faker = Faker::create();
	echo 'Email Address: ' . $faker->unique()->email;

Insert data

$faker = Faker::create();
	'username' => $faker->userName(),
	'password' => $faker->password(),
	'about' => $faker->sentence(),	
	'created_at' => \Carbon\Carbon::now(),
	'Updated_at' => \Carbon\Carbon::now(),

$comment = new Comment();
$comment->body = $faker->paragraphs(1, true);
$comment->user_id = $faker->numberBetween(1, 100);
$comment->post_id = $faker->numberBetween(1, 50);

$order = new Order();
$order->customer_name = $faker->name();
$order->customer_email = $faker->unique()->email();
$order->total_amount = $faker->randomFloat(2, 50, 500);
$order->status = $faker->randomElement(['pending', 'processing', 'shipped']);

$product = new Product();
$product->name = $faker->words(3, true);
$product->description = $faker->paragraphs(3, true);
$product->price = $faker->randomFloat(2, 10, 100);
$product->quantity = $faker->numberBetween(1, 100);

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.