phpjsonlaravellaravel-migrationslaravel-seeding

How to Seed Data from JSON Files in Laravel?


I have some JSON files, and I want to use them to seed my database in Laravel. Could someone guide me on how to achieve this? Specifically, I want to:

  1. Migrate the database tables required for the JSON data.

  2. Use Laravel's Seeder class to read the JSON files and insert the data into the database.

For context, here is an example of the JSON file (data.json) I’m working with. It contains an array of user data:

[
  {
    "name": "John Doe",
    "email": "john@example.com",
    "age": 30
  },
  {
    "name": "Jane Smith",
    "email": "jane@example.com",
    "age": 25
  }
]

Solution

  • use Illuminate\Database\Seeder;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\File;
    
    class UsersTableSeeder extends Seeder
    {
        public function run()
        {
            // Path to your JSON file
            $jsonFile = base_path('database/seeders/data.json');
    
            // Read and decode the JSON file
            $jsonData = json_decode(File::get($jsonFile), true);
    
            // Insert data into the database
            DB::table('users')->insert($jsonData);
        }
    }