SPA with Laravel 5 and Angular: Working with Faker to create dummy data

During development, dummy data is very important. I have seen that dummy data really helps speed up the development. Those coming from Drupal would know how good the Devel generate module use to work. So, in Laravel we can use the Faker library to create dummy data.

Introduction

As mentioned, I will be using the Faker library to seed a lot of dummy data. We will be using the Faker libraryfzaninotto/Faker for this. In our composer.json file in require-dev section we will add the following:

[json]
“require-dev”: {
“phpunit/phpunit”: “~4.0”,
“phpspec/phpspec”: “~2.1”,
“fzaninotto/faker”: “dev-master”
},
[/json]

After this once we run composer update or even composer update –dev we will get the required library.

Once this is done, we will write some seeding code so that when we run db:seed, we get some good number of randomly generated posts.

We will first create some random users and then create some random posts which will relate to these random users.

public function run()
{
    // first truncate the table
    DB::table('users')->truncate();
  
    // create the instance of faker
    $faker = Faker\Factory::create();
  
    // run the loop for inserts
    for ($i = 0; $i < 10; $i++) { $user = new User; $user->name = $faker->name;
        $user->email = $faker->email;
        $user->password = Hash::make($faker->password);
        $user->save();
    }
}
 
public function run()
{
    // first truncate the table
    DB::table('posts')->truncate();
  
    // create the instance of faker
    $faker = Faker\Factory::create();
  
    // run the loop for inserts
    for ($i = 0; $i < 50; $i++) { $userId = rand(1,10); $user = User::find($userId); $post = new Post; $post->title = $faker->sentence(6);
        $post->body = $faker->text;
        $post->user_id = $userId;
        $post->save([
            'user' => $user,
            'post' => $post
        ]);
    }
}

Once this is done, we can see that we have about 10 users and 50 posts which has reference to the 10 users present in the system. This is a good starting point for us to start creating an app which will work with the REST API which I will show in the next tutorial on this series.

The entire code base can be found on this release branch on github.