A simple way to seed database with json data in files

A simple way to seed database with json data in files

  1. Copy your json format data file to one of Laravel’s directories, preferably database.
  2. create a seeder file:
    php artisan make:seeder JsondataTableSeeder
  3. Modify the seeder class
<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;

class JsondataTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Load the file
        $path = base_path() . '/database/data.json';
        $file = File::get($path);
        $data = json_decode($file, true);

        // Insert into the database
        DB::table('jsondata')->insert($data);
    }
}

4. Add the newly created JsondataTableSeeder to DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(JsondataTableSeeder::class);
    }
}

5. run seeding command

php artisan db:seed --class=JsondataTableSeeder

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.