So you have a database filled with (mostly correct) data and you want to create a Laravel seeder with it than can be initially not be connected to any database?

Marc C
Nov 22, 2024

--

Easy answer. I got the json file from my database (in this case phpMyAdmin.)

Which gave me a mostly usable file like this:

In my case, lines 2 to 5 needed to be deleted (and some final closing brackets to match)

Then my seeders/DefaultRoomsSeeder.php looks like this:

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

class DefaultRoomsSeeder extends Seeder
{
/**
* Run the database seeds → php artisan db:seed --class=DefaultRoomsSeeder
*/
public function run(): void
{
$jsonFilePath = database_path('seeders/default_rooms.json');

if (File::exists($jsonFilePath)) {
$jsonData = File::get($jsonFilePath);

$default_rooms = json_decode($jsonData, true);

DB::table('default_rooms')->insert($default_rooms);
} else {
throw new \Exception("JSONファイル見つからない: $jsonFilePath");
}

}
}

Simple as that.

--

--

Marc C
Marc C

Written by Marc C

Both a creative and critical thinker, I am a programmer, bicycle rider, and woodworker, based in Japan.

No responses yet