How to seed JSON data in Laravel

JSON needs no introduction. In the simplest words it is a syntax for storing and exchanging information with server. But the use of JSON is not only limited to exchanging data with server, we can do a lot more than that. Now coming to the context of this article, seeding is well familiar technique for developers. If you are new with this term let me tell you what it is. Whenever you build a new application, there is a need of some initial or master data, we provide this data in-order to kick-start the application. Seeding technique is used to provide this data in a well structured and safe format.

Now in seeding in Laravel, often comes a need that you need to put a large amount of data. Now this data may be in PHP array or in JSON format or in none. If it is a PHP array then there is no issue, if it is in JSON then no issue, if it is in some other format, you should first convert it into JSON and proceed to following steps to seed JSON data in Laravel.

How to seed JSON data

  • Put your Json in a text file and save it as FILE_NAME.json
  • Fetch your Json file in laravel using file_get_contents.
    Something like this –

    $jsonData = json_decode(file_get_contents("FILE_NAME.json"), true);
  • Now you have your file content in a php┬ávariable.
  • Now we can apply a simple foreach loop and access each key and value. Make sure your JSON is linear and one dimensional. Any nesting will affect the seeding process.
  • While fetching each record from the JSON, just insert it in DB using simple insert command like this –
foreach($jsonData as $value){
    $tableArray = [
        'table_column' => $value['KEY']            
    ];
    //creating the record in database
    \DB::table('TABLE_NAME')->insert($tableArray );
}

This way you can seed the values in database from JSON data. Here’s the complete code –

public function run()
{
    // Fetching json data form file
    $jsonData = json_decode(file_get_contents("FILE_NAME.json"), true);

    // Creating array and inserting records
    foreach($jsonData as $value){
        $tableArray = [
            'table_column' =>$value['KEY']
        ]; 
        //creating the record in database 
        $icd = \DB::table('TABLE_NAME')->insert($tableArray ); 
 } 
}

Do let me know in the comment section, if you face any issues.