How to seed JSON data into database in laravel

Suppose we have created a JSON file for a particular task like a country list and we need to use it at multiple locations and process some operations like sorting, searching, filtering, etc. So we can handle it more easily and save processing time with databases instead of files.

But converting JSON Data into the database is a hard process only if we approach it manually. Here in Laravel, we can easily add those data into a table with the help of a seeder programmatically whenever required.

Let’s assume your application is running and the database is configured.

Create or Download JSON file

In this application, we need a JSON file that contains country names and codes. You can download it online or create a new one. You can add this file at any location.

Here we will create a new directory into the database directory by JSON name and move our JSON file in it.

Create Model & Migrations

To store JSON data from a file we need a model. So let’s create a model using the below command:

php artisan make:model CountryCode -m

It will create CountryCode.php at App\Models Directory.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CountryCode extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'dial_code',
        'code',
    ];
}

While creating we have passed -m so it will create a migration file with it. Open the migration file and make relevant changes.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCountryCodesTable extends Migration
{
    public function up()
    {
        Schema::create('country_codes', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('dial_code');
            $table->string('code');
            $table->timestamps();
        });
    }
   public function down()
    {
        Schema::dropIfExists('country_codes');
    }
}

As per migration, we have created three new columns besides id, created_at, and updated_at columns: name, dial_code, and code.

To run migration execute the given below command into a terminal:

php artisan migrate

It will generate a database table by name country_codes.

Create Seeder

In this step, we will create a seeder for our model and write logic to read JSON files and insert JSON file data into our database. To create a seeder enter the below command into a terminal :

php artisan make:seeder CountryCodeSeeder

The above command will create a database/seeders/CountryCodeSeeder.php file in your application. Let’s make some as per requirement :

<?php

namespace Database\Seeders;

use App\Models\CountryCode;
use Illuminate\Database\Seeder;
use File;

class CountryCodeSeeder extends Seeder
{
    public function run()
    {
        CountryCode::truncate();
        $json_data = File::get("database/Json/CountryCodes.json");
        $countries = json_decode($json_data);

        foreach ($countries as $key => $value) {
            CountryCode::create([
                "name" => $value->name,
                "dial_code" => $value->dial_code,
                "code" => $value->code
            ]);
        }
    }
}

As per logic, first of all, it will read JSON files using File. Then it will use the json_decode() function to convert JSON data into an array so we can loop through it. At last, it will create records using a loop into our CountryCodes model.

Seeding Data into Database

We can directly run our seeder but setting our seeder into Database Seeder is best practice in an enterprise application. So will register it into our DatabaseSeedder.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call([
            CountryCodeSeeder::class,
        ]);
    }
}

Finally, We have created our seeder and it’s time to seed our database. Enter the below command into a terminal :

php artisan db:seed

If you don’t want to register it into Database Seeder then you can simply run the below command into your terminal and seed data :

php artisan db:seed --class=CountryCodeSeeder

Note: Sometimes after creating a new seeder you face an error, so you might require to regenerate Composer’s autoloader.