Laravel 11 Create Seeder with CSV File

Websolutionstuff | Sep-16-2024 | Categories : Laravel

Hello, Laravel developers! In this article, I'll show you how to create a seeder in Laravel 11 that imports data from a CSV file into the database. We'll use a seeder to read the CSV file and automatically import the data when we run the db:seed command.

This method is especially useful when you need to insert large amounts of data, like country or city information. Instead of manually handling it every time, you can set up a seeder that reads the CSV file and imports the data into the database with a simple artisan command.

Laravel 11 Create Seeder with CSV File

Laravel 11 Create Seeder with CSV File

 

 Step 1: Install Laravel 11

In this step, we'll install the laravel 11 application using the following command.

composer create-project --prefer-dist laravel/laravel laravel-11-example

 

Step 2: Create CSV File

Next, we'll create a country CSV file with the name and code.

database/data/country.csv

country CSV file

 

Step 3: Create Model and Migration

Then, we'll create a seeder using the following command.

php artisan make:migration create_countries_table

Migration:

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

Now, run the migration using the following command.

php artisan migrate

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'
    ];
}

 
Step 4: Create Seeder

Next, we'll create country seeder using the following command.

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);
    }
}

Then, run the seeder using the following command.

php artisan db:seed --class=CountrySeeder

 


You might also like:

Recommended Post
Featured Post
How To Import Export Excel & CSV File In Laravel 10
How To Import Export Excel & C...

In this article, we will see how to import and export Excel & CSV files in laravel 10. Here, we will learn about lar...

Read More

Mar-08-2023

How To Use Google Recaptcha V2 In Laravel 9
How To Use Google Recaptcha V2...

In this article, we will see how to use google ReCaptcha v2 in laravel 9. Google ReCaptcha is used for advance...

Read More

Jun-14-2022

How to Handle Exception in PHP with Example
How to Handle Exception in PHP...

Hey there, Ever found yourself scratching your head over unexpected errors in your PHP code? Fret not, because today, we...

Read More

Dec-15-2023

Laravel 8 Artesaos SEOTools Tutorial
Laravel 8 Artesaos SEOTools Tu...

Hello Devs, In this tutorial we will learn how to use SEOTools in laravel 8. we will give you example of se...

Read More

Jun-07-2021