Seeding Laravel and Django with Fake JSON Data
Laravel and Django both have built-in seeding systems (Laravel's Seeder/Factory classes, Django's fixtures and management commands). Most tutorials show you how to generate data inline with Faker — but importing pre-generated JSON is often faster and easier to review. This guide covers both approaches for each framework.
Laravel: Seeding from a JSON File
Step 1: Generate your data
Open Dummy JSON Generator, build a schema matching your Eloquent model, and export as JSON. Save it to database/seed-data/users.json.
Step 2: Write the Seeder
// database/seeders/UserSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class UserSeeder extends Seeder
{
public function run(): void
{
$path = database_path('seed-data/users.json');
$users = json_decode(file_get_contents($path), true);
foreach ($users as $userData) {
User::create([
'name' => $userData['fullName'],
'email' => $userData['email'],
'password' => Hash::make('password'), // dev-only default
'city' => $userData['city'],
'status' => $userData['status'],
]);
}
$this->command->info(count($users) . ' users seeded.');
}
}Step 3: Register and run
// database/seeders/DatabaseSeeder.php
public function run(): void
{
$this->call([
UserSeeder::class,
]);
}php artisan db:seed
# or fresh migrate + seed:
php artisan migrate:fresh --seedBulk Insert for Large Datasets (Faster)
For thousands of records, use chunked bulk inserts instead of individual create() calls:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Carbon\Carbon;
$users = json_decode(file_get_contents($path), true);
collect($users)->chunk(500)->each(function ($chunk) {
$rows = $chunk->map(fn ($u) => [
'id' => Str::uuid(),
'name' => $u['fullName'],
'email' => $u['email'],
'password' => bcrypt('password'),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
])->toArray();
DB::table('users')->insert($rows);
});Laravel: Using JSON in Factories (Alternative to Faker)
If you prefer keeping the Factory pattern but want fixed realistic data instead of random Faker calls on every run:
// database/factories/UserFactory.php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
protected static ?array $pool = null;
protected static int $index = 0;
public function definition(): array
{
if (self::$pool === null) {
self::$pool = json_decode(
file_get_contents(database_path('seed-data/users.json')),
true
);
}
$user = self::$pool[self::$index % count(self::$pool)];
self::$index++;
return [
'name' => $user['fullName'],
'email' => $user['email'],
'password' => bcrypt('password'),
];
}
}Django: Seeding from a JSON Fixture
Django has native fixture support — JSON files that map directly to your models, loaded with a single management command.
Step 1: Generate matching data
Django fixtures need a specific structure with model, pk, and fields keys. Generate your raw data with Dummy JSON Generator, then wrap it in this structure with a small script:
# convert_to_fixture.py
import json
with open('generated-users.json') as f:
raw_users = json.load(f)
fixture = []
for i, user in enumerate(raw_users, start=1):
fixture.append({
"model": "myapp.user",
"pk": i,
"fields": {
"full_name": user["fullName"],
"email": user["email"],
"city": user["city"],
"status": user["status"],
"created_at": user["createdAt"],
}
})
with open('myapp/fixtures/users.json', 'w') as f:
json.dump(fixture, f, indent=2)
print(f"Wrote {len(fixture)} records to fixture.")Step 2: Load the fixture
python manage.py loaddata users.jsonDjango automatically finds users.json in any fixtures/ directory in your installed apps.
Django: Custom Management Command (More Control)
For more control than fixtures allow — like generating related objects or handling foreign keys — write a custom management command:
# myapp/management/commands/seed_users.py
import json
from django.core.management.base import BaseCommand
from myapp.models import User
class Command(BaseCommand):
help = 'Seed users from generated JSON data'
def add_arguments(self, parser):
parser.add_argument('--file', type=str, default='seed-data/users.json')
def handle(self, *args, **options):
with open(options['file']) as f:
users_data = json.load(f)
users = [
User(
full_name=u['fullName'],
email=u['email'],
city=u['city'],
status=u['status'],
)
for u in users_data
]
User.objects.bulk_create(users, batch_size=500, ignore_conflicts=True)
self.stdout.write(self.style.SUCCESS(f'Seeded {len(users)} users.'))python manage.py seed_users --file=seed-data/users.jsonbulk_create with batch_size=500 is dramatically faster than calling .save() in a loop — typically 10–20x faster for large datasets.
Recommended Pattern for Both Frameworks
- Generate a realistic dataset once with Dummy JSON Generator, matching your model's field names
- Commit the JSON file to your repository under a
seed-data/directory - Write a thin seeder/management command that reads the file and bulk-inserts
- Document the seed command in your README so new team members run it on setup
- Regenerate the file periodically (e.g., quarterly) to keep the dataset fresh
This approach is faster than Faker-in-a-loop seeders, produces consistent data across team members' machines, and is easy to review in a pull request since the data is a static file rather than generated at runtime.