DEV Community

Ayowande Oluwatosin
Ayowande Oluwatosin

Posted on

Efficient Data Generation in Laravel: Leveraging JSON Files && Laravel Factory for Your Database

Hello! Generating dummy or fake data for testing purposes is a common need in software development, and Laravel provides several ways to achieve this. Let's explore some of the methods commonly used in Laravel to generate test data:

  1. Using a JSON file to store dummy data, you can follow these steps:
  2. Create a folder named "data" inside the "database" folder of your Laravel project.

Inside the "data" folder, create a file named "category.json" and add the following JSON data to it:

[
    {
        "id": 1,
        "name": "Electronics"
    },
    {
        "id": 2,
        "name": "Clothing"
    },
    {
        "id": 3,
        "name": "Books"
    }
]

Enter fullscreen mode Exit fullscreen mode

This JSON data represents a list of categories with their respective IDs and names.

Next, you can read the JSON data from the file and use it in your Laravel application. For example, you can use the DatabaseSeeder.php

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        //get the data
        $data = File::get('database/data/category.json');
        //convert to array, of the asscociative kind
        $categories= collect(json_decode($data, true));
        $categories->each(function($category){
            DB::table('category')->insert([
                'category_name'=>$category['name'],
                'category_id'=>$category['id']
            ]);
        });
    }
}

Enter fullscreen mode Exit fullscreen mode
  1. Using faker Laravel comes with the Faker library by default, which allows you to create fake data like names, addresses, emails, and more.
  • create a factory for a post modal

php artisan make:factory PostFactory

  • In the PostFactory
class PostFactory extends Factory
{
 public function definition(): array
    {
        $title = fake()->unique()->sentence();
        $slug = Str::slug($title);
        return [
            'title'=>$title,
            'slug'=>$slug,
            'description'=>fake()->paragraph(9, true),
            'category'=>Category::inRandomOrder()->value('category_id'),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, in the DatabaseSeeder.php,

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        //create 20 rows in the table
        Post::factory()->count(20)->create();
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, what if we want a relationship to build as well for the post. For instance, where an author has many posts, and we want a fake data for that as well??

Top comments (0)