Laravel Advance | How to Create Seeder with JSON data in Laravel?

In this short tutorial, we will cover a laravel seed from a JSON file example. I explained simply how to create a seeder with JSON file in laravel. if you have a question about laravel seeder from the JSON file then I will give a simple example with a solution. we will help you to give an example of laravel seeder JSON.

Sometimes we need to read the long JSON files and store that data in your database and we need to do maybe in every setup then we always choose seeder for that. so here I will give you a very simple example of how to create a seeder with JSON data in laravel and you can use this example with laravel 6, laravel 7, and laravel 8 versions.

Step 1: Create JSON File

in the first step, we will create a country JSON file with the name and code. so you can create a data folder inside the database folder and put that file as bellow preview:

database/data/country.json

[
{"name":"india","code":"IN"}
]

Step 2: Create Seeder and Country Model

here, we will create migration for countries table. so let’s create migration as bellow:

php artisan make:migration create_countries_table

database/migrations/your_migtion_file.php

<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;class CreateCountriesTable extends Migration{/*** Run the migrations.** @return void*/public function up(){Schema::create('countries', function (Blueprint $table) {$table->id();$table->string('name');$table->string('code');$table->timestamps();});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('countries');}}

now let’s run the migration:

php artisan migrate

next, add a soft delete facade in the user model as like bellow:

app/Models/County.php

<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;class Country extends Model{use HasFactory;protected $fillable = ['name', 'code'];}

Step 3: Create Seeder

In this step, we need to create add seeder for country lists.

Create Seeder with bellow command

php artisan make:seeder CountrySeeder

database/seeders/CountrySeeder.php

<?phpnamespace Database\Seeders;use Illuminate\Database\Seeder;use App\Models\Country;use File;class CountrySeeder extends Seeder{/*** Run the database seeds.** @return void*/public function run(){Country::truncate();$json = File::get("database/data/country.json");$countries = json_decode($json);foreach ($countries as $key => $value) {Country::create(["name" => $value->name,"code" => $value->code]);}}}

now let’s run seeder:

php artisan db:seed --class=CountrySeeder

I hope it can help you.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store