admin管理员组

文章数量:1122846

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": "[email protected]",
    "age": 30
  },
  {
    "name": "Jane Smith",
    "email": "[email protected]",
    "age": 25
  }
]

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": "[email protected]",
    "age": 30
  },
  {
    "name": "Jane Smith",
    "email": "[email protected]",
    "age": 25
  }
]
Share Improve this question asked Nov 21, 2024 at 11:46 Muhammed SalamaMuhammed Salama 216 bronze badges 2
  • in your seeder class you can first read the json data from the file and write your logic to map those data with your database table. Then using eloquent or raw query you can store that data into the table. – sandip bharadva Commented Nov 21, 2024 at 12:00
  • What exactly is the problem? Migrating the database, such that the proper columns are created, or reading the data itself? – Nico Haase Commented Nov 21, 2024 at 12:46
Add a comment  | 

1 Answer 1

Reset to default 1
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);
    }
}

本文标签: phpHow to Seed Data from JSON Files in LaravelStack Overflow