Generate fake data using Faker and Factory in Laravel

Generate fake data using Faker and Factory in Laravel

Category: Laravel   Updated by Ryan Dhungel

Whenever you want to test your Laravel application, you obviously need a lot of data in your database. However creating them manually all the time is not ideal and it takes a lot of time and slow down your development process.

Using Factory and Faker that ships with Laravel, Its not that hard to generate thousands of posts in matter of seconds. With a bit of setup, It can be done. I am going to show you how you can generate fake data using Faker and Factory in Laravel.

Following this step by step tutorial is easy.


  • Make sure you have fresh install of laravel
  • Create a database and inform .env


Create a Post model

php artisan make:model Post -m​

Add title and body fields to the post migration

Schema::create('posts', function (Blueprint $table) {

Run the migration

php artisan migrate​

Go to database/factories/ModelFactory.php. There you will see factory User model already defiened. We need to create our own for Post model.

Put the following code right below. This is for post model, You can modify it for other models adding more fields as needed.
Here we are using faker to create title and body fields

$factory->define(App\Post::class, function(Faker\Generator $faker) {
return [
'title' => $faker->sentence(10),
'body' => $faker->sentence(50),

Create database seeder

php artisan make:seeder PostTableSeeder​

Go to database/seeds/PostTableSeeder.php. Inside run function we are using factory to create posts, 500 of them.

public function run()
factory(App\Post::class, 500)->create()->each(function($post){

Now go to database/seeds/DatabaseSeeder.php. Inside run function, call for the seeder class PostTableSeeder.

public function run()

Make sure you have protected fillable fields defiened in Post model.

protected $fillable = ['title', 'body'];​

Now run database seeder

php artisan db:seed​

You have just created 500 fake posts. Check your database.


In this short tutorial, you learned how to create fake data using Factory and Faker. If you are confused about the entire process, I suggest you to repeat it a few times. It always gets confusing at first but once you repeat, It will make perfect sense.

I hope this will help you speed up your development process. Enjoy Laravel.

Back to articles