---
description: >-
  https://www.itsolutionstuff.com/post/laravel-seeder-from-csv-file-exampleexample.html
---

# Laravel Seeder from CSV File Example (ok)

C:\xampp\htdocs\reset\database\migrations\2022\_05\_20\_190911\_create\_countries\_table.php

```
<?php
use 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');
  }
}
```

C:\xampp\htdocs\reset\app\Models\Country.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Country extends Model {
  use HasFactory;
  protected $table      = 'countries';
  protected $primaryKey = 'id';
  protected $fillable   = [
    'name', 'code',
  ];
}
```

C:\xampp\htdocs\reset\database\seeders\CountrySeeder.php

```
<?php
namespace Database\Seeders;
use App\Models\Country;
use Illuminate\Database\Seeder;
class CountrySeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    Country::truncate();
    $csvFile = fopen(base_path("database/data/country.csv"), "r");
    $firstline = true;
    while (($data = fgetcsv($csvFile, 2000, ",")) !== FALSE) {
      if (!$firstline) {
        Country::create([
          "name" => $data['0'],
          "code" => $data['1'],
        ]);
      }
      $firstline = false;
    }
    fclose($csvFile);
  }
}
```

C:\xampp\htdocs\reset\database\data\country.csv

```
"record","name","code"
,"A 1","B 1"
,"A 12","B 12"
,"A 31","B 13"
,"A 14","B 14"
,"A 15","B 15"
,"A 16","B 16"
,"A 17","B 17"
,"A 18","B 18"
,"A 19","B 19"

```

![](https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FgA2UWZPPgrdW8e5ZdL6q%2FScreenshot_8.png?alt=media\&token=b3acbb1d-274b-4e77-984e-0820e0fc9c04)

## Laravel Seeder from CSV File Example

By Hardik Savani August 10, 2021 Category : Laravel![](https://a.vdo.ai/core/assets/img/cross.svg)PlayUnmuteLoaded: 1.15%Fullscreen[![VDO.AI](https://a.vdo.ai/core/assets/img/logo.svg)](https://vdo.ai/?utm_medium=video\&utm_term=itsolutionstuff.com\&utm_source=vdoai_logo)[![](https://go.ezodn.com/charity/http/charity-ads.s3.amazonaws.com/charity_ads/1079/728x90.png)](https://go.ezodn.com/ads/charity/proxy?p_id=b3e016a1-6f5b-49c4-485e-d13e6e4071ed\&d_id=77568\&imp_id=2269492628375999\&c_id=1079\&l_id=10016\&url=https%3A%2F%2Fwww.directrelief.org%2Femergency%2Fukraine-crisis%2F\&ffid=1\&co=VN)Hi Dev,

In this short tutorial we will cover an laravel seeder from csv file. We will look at example of laravel seed from csv file. you'll learn laravel seeder csv file. Here you will learn laravel seeder from csv.

Sometime we need to read long csv file and store that data in you database and we need to do maybe in every setup then we always choose seeder for that. so here i will give you very simple example of how to create seeder with csv data in laravel and you can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.

**Step 1: Create CSV File**

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

database/data/country.csv

![](https://www.itsolutionstuff.com/upload/laravel-seeder-csv.png)

**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

```
<?php  use 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');    }}
```

[![](https://go.ezodn.com/charity/http/charity-ads.s3.amazonaws.com/charity_ads/1079/300x250.png)](https://go.ezodn.com/ads/charity/proxy?p_id=b3e016a1-6f5b-49c4-485e-d13e6e4071ed\&d_id=77568\&imp_id=2234640684379984\&c_id=1079\&l_id=10016\&url=https%3A%2F%2Fwww.directrelief.org%2Femergency%2Fukraine-crisis%2F\&ffid=1\&co=VN)[![](https://go.ezodn.com/charity/http/charity-ads.s3.amazonaws.com/charity_ads/1094/300x250.png)](https://go.ezodn.com/ads/charity/proxy?p_id=b3e016a1-6f5b-49c4-485e-d13e6e4071ed\&d_id=77568\&imp_id=2234640684379984\&c_id=1094\&l_id=10016\&url=https%3A%2F%2Ffundraise.pencilsofpromise.org%2Fgive%2F405130%2F%23!%2Fdonation%2Fcheckout%3Fc_src%3Dadsezoic\&ffid=1\&co=VN)[![](https://go.ezodn.com/charity/http/charity-ads.s3.amazonaws.com/charity_ads/1094/300x250.png)](https://go.ezodn.com/ads/charity/proxy?p_id=b3e016a1-6f5b-49c4-485e-d13e6e4071ed\&d_id=77568\&imp_id=2234640684379984\&c_id=1094\&l_id=10016\&url=https%3A%2F%2Ffundraise.pencilsofpromise.org%2Fgive%2F405130%2F%23!%2Fdonation%2Fcheckout%3Fc_src%3Dadsezoic\&ffid=1\&co=VN)

now let's run migration:

```
php artisan migrate
```

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

app/Models/County.php

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

Read Also: [How to create database seeder in Laravel 5.7?](https://www.itsolutionstuff.com/post/how-to-create-database-seeder-in-laravel-57example.html)

**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

```
<?php  namespace Database\Seeders;  use Illuminate\Database\Seeder;use App\Models\Country;  class CountrySeeder extends Seeder{    /**     * Run the database seeds.     *     * @return void     */    public function run()    {        Country::truncate();          $csvFile = fopen(base_path("database/data/country.csv"), "r");          $firstline = true;        while (($data = fgetcsv($csvFile, 2000, ",")) !== FALSE) {            if (!$firstline) {                Country::create([                    "name" => $data['0'],                    "code" => $data['1']                ]);                }            $firstline = false;        }           fclose($csvFile);    }}
```

[![](https://go.ezodn.com/charity/http/charity-ads.s3.amazonaws.com/charity_ads/1093/300x250.png)](https://go.ezodn.com/ads/charity/proxy?p_id=b3e016a1-6f5b-49c4-485e-d13e6e4071ed\&d_id=77568\&imp_id=6080595350408435\&c_id=1093\&l_id=10016\&url=https%3A%2F%2Fwww.directrelief.org%2Femergency%2Fukraine-crisis%2F\&ffid=1\&co=VN)[![](https://go.ezodn.com/charity/http/charity-ads.s3.amazonaws.com/charity_ads/1079/300x250.png)](https://go.ezodn.com/ads/charity/proxy?p_id=b3e016a1-6f5b-49c4-485e-d13e6e4071ed\&d_id=77568\&imp_id=6080595350408435\&c_id=1079\&l_id=10016\&url=https%3A%2F%2Fwww.directrelief.org%2Femergency%2Fukraine-crisis%2F\&ffid=1\&co=VN)[![](https://go.ezodn.com/charity/http/charity-ads.s3.amazonaws.com/charity_ads/1079/300x250.png)](https://go.ezodn.com/ads/charity/proxy?p_id=b3e016a1-6f5b-49c4-485e-d13e6e4071ed\&d_id=77568\&imp_id=6080595350408435\&c_id=1079\&l_id=10016\&url=https%3A%2F%2Fwww.directrelief.org%2Femergency%2Fukraine-crisis%2F\&ffid=1\&co=VN)

now let's run seeder:

Read Also: [How to Run Specific Seeder in Laravel?](https://www.itsolutionstuff.com/post/how-to-run-specific-seeder-in-laravelexample.html)

```
php artisan db:seed --class=CountrySeeder
```

now you can see bellow added country lists on your table:

![](https://www.itsolutionstuff.com/upload/laravel-seeder-json-1.png)

I hope it can help you.
