Skip to content

Seed Database From JSON File in Laravel

laravel seed database from json file

We’re going to have a look, in just a few steps, at how to seed the database with data that come from a JSON file within our application.

In this example, we’ll use the movies.json file to seed the movies table with the top 100 movies ranked by IMDB.

Click here to inspect the JSON file we’re gonna be using.

Maybe you prefer the video version of this tutorial?

 

Let’s get started!

Create the JSON file

I already have the JSON file prepared right here, but feel free to use your own file and adapt the code to your needs.

I put the JSON file in the storage/app/json folder.

It may not be the best place to store it, but for the purpose of this example, it will do just fine.

Create the corresponding Model

We need a movies table so let’s go ahead and create an Eloquent Model Class.

Open up the terminal and write:

php artisan make:model Movie

Open the Movie Model and define the name of the table and the fields that we want to get filled.

Create the migration

Now that we have the Model set up, let’s go ahead and create a migration for our table.

In the terminal, write:

php artisan make:migration create_movies_table

Open the migration file and let’s add the title and the id_imdb columns so that it matches the structure of the JSON data from our file.

Now let’s run the migration by saying:

php artisan migrate


Create the Seeder Class

Now comes the fun part.

We have to create a Seeder Class that reads the JSON file, extracts the data, and then inserts or updates it into the database.

Inside the terminal, let’s say:

php artisan make:seeder MovieTableSeeder

We’re going to use the Storage facade to read the file from the storage.

We decode the data into associative arrays.

Then we iterate over each movie and insert it into the database.

 

Call the Seeder

Now that we have the core logic ready to go, we must invoke the MovieTableSeeder from the DatabaseSeeder Class which comes out of the box with Laravel.

 

Everything should be alright at this point and let’s run the seeder by saying:

php artisan db:seed

Check the database to see if the table has been populated with the data from the JSON file.


Let me know what you think about this article in the comments section below.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.   
  

Comments