10 July 2018

How to insert JSON file data into MySQL in php using Laravel

A simple example demonstrating how to insert JSON file data into MySQL database table using Laravel

Steps to Save/Insert JSON File into MySQL Database table using Laravel (PHP)

  • Create and store the JSON File in Laravel Storage folder.
  • Read the JSON file contents inside the Storage folder.
  • json_decode the file contents.
  • Insert decoded data into MySQL database table.

This will be a simple example showing, how we can save or insert date inside a JSON file into our database table. We will be using the Routes and a JSON File for this tutorial. So let's being.

Create and Store the JSON file in Laravel Storage folder

Its up to you from where you want to read the file, it can be fetched from a URL source or from any were which is accessible your application. In this example we will save our JSON file in the Storage folder.

Read the JSON file contents inside the Storage folder

We will using PHP file_get_contents() Function to read the JSON file into a string. This function will read the contents of JSON file into a string and will use memory mapping techniques for the read operation.

JSON DECODE the file content

PHP json_decode function only works with UTF-8 encoded strings.

As our requirement is decode the JSON, so that we can do the required operation and then insert the data into the database table.

Insert decoded data into MySQL database table

Once the JSON file is decode we can use a loop to iterate through each records and then insert in the database table. The main part of this step is, how we will map a database columns and the JSON key values. While we loop through our decoded data, we will convert the keys into the same values as we have in the database table.

<!--web.php file-->
Route::get('/insert-json-file-to-database-table', function(){
	$json = file_get_contents(storage_path('demo.json'));
	$objs = json_decode($json,true);
	foreach ($objs as $obj)  {
		foreach ($obj as $key => $value) {
			$insertArr[str_slug($key,'_')] = $value;
		}
		DB::table('examples')->insert($insertArr);
	}
	dd("Finished adding data in examples table");
});

Laravel str_slug function help us to convert the keys so as to match with our database table column names and finally we insert our array into the table. If you are having a huge data to be inserted in the table, you can use Laravel transaction method. So that in case of any failure we can rollback the transaction and figure our what went wrong and debug later.

Hope this helps. Cheers!

Recent resources

Advertisement

Advertisement