A simple way to seed database with json data in files
- Copy your json format data file to one of Laravel’s directories, preferably
.database
- create a seeder file:
JsondataTableSeederphp artisan make:seeder
- 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
to JsondataTableSeeder
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