How To Seed CSV Data in Laravel 10 Example Tutorial

Reading Time: 5 minutes
559 Views

Data seeding is a basic part of database administration in web development, allowing developers to rapidly and efficiently load their databases with initial data. You can smoothly seed your database with CSV data in Laravel, a strong PHP framework, which is a common and convenient format for importing and maintaining massive datasets.

In this video, we will walk you through the process of seeding CSV data in Laravel 10, providing you with the information and tools you need to properly manage your database.

Database seeding is the process in which we feed test data to tables. You can insert data either using Faker library, manual data or means of some more data sources like CSV, JSON.

Read More: Laravel 10 Mailable Email Template Components Tutorial

By the end of this lesson, you will be able to simply seed CSV data into your Laravel 10 database.

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Laravel Model & Migration

Open project terminal and run this command to create model and migration file.

php artisan make:model Country -m

It will create two files –

  • Model – Country.php inside /app/Models folder
  • Migration file – xxx_create_countries_table inside /database/migrations folder.

Open file and write this complete code into it,

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('sortname');
            $table->string('name');
            $table->string('phonecode');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('countries');
    }
};

Read More: How To Create a Custom 404 Page in Laravel 10 Tutorial

Open model file Country.php and write this complete code into it,

<?php

namespace App\Models;

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

class Country extends Model
{
    use HasFactory;

    public $timestamps = false;
}

Run Migration

Next, we need to migrate migration files.

php artisan migrate

This command will create tables inside database. It will create countries table in database.

Prepare CSV File (A Set of Data)

As you have table countries in which columns as id, name, sortname, phonecode.

You have a CSV file in which the columns will be ID, Sortname, Name and Phonecode.

When you will download the given file it will be in .txt format.

Rename file into .csv and place this countries.csv file inside /public/data folder.

Open countries.csv file, you should see –

Create Laravel Data Seeder

Next, you need to create a seeder file.

php artisan make:seeder CountrySeeder

It will create a file CountrySeeder.php inside /database/seeders folder.

Open file and write this complete code into it,

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Country;

class CountrySeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        //Country::truncate();

        $csvFile = fopen(public_path("data/countries.csv"), "r");

        $firstline = true;
        while (($data = fgetcsv($csvFile, 2000, ",")) !== FALSE) {
            if (!$firstline) {
                Country::create([
                    "sortname" => $data['1'],
                    "name" => $data['2'],
                    "phonecode" => $data['3']
                ]);
            }
            $firstline = false;
        }

        fclose($csvFile);
    }
}

Laravel Data Seeding

Open project terminal and run this artisan command,

php artisan db:seed --class=CountrySeeder

Read More: Laravel 10 Eloquent Has One Through Relationship Tutorial

It will seed countries data into table.

That’s it.

We hope this article helped you to learn How To Seed CSV Data in Laravel 10 Example Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more