Sling Academy
Home/PHP/Laravel & Eloquent: Seeding a CSV file into a MySQL database

Laravel & Eloquent: Seeding a CSV file into a MySQL database

Last updated: February 13, 2024

Overview

In this tutorial, we will explore how to seed a CSV file into a MySQL database using Laravel, a popular PHP framework well-known for its elegant syntax and robust features. Laravel’s Eloquent ORM makes interacting with databases incredibly intuitive. By the end of this guide, you’ll have a comprehensive understanding of how to efficiently import a CSV file into your MySQL database using Laravel’s seeders.

Prerequisites

  • Basic understanding of PHP and Laravel
  • Laravel installation on your system
  • A MySQL database
  • A CSV file you want to import

Step-by-Step Instructions

Step 1: Setting Up the Environment

Ensure Laravel is installed and configured correctly on your machine. You also need to have a MySQL database ready. If needed, you can create a new database using phpMyAdmin or the MySQL command line:

CREATE DATABASE your_database_name;

Step 2: Creating the Model and Migration

Begin by creating a new model and migration for the table into which you’ll import the CSV data. You can do this easily with Artisan commands:

php artisan make:model MyModel -m

In the generated migration file located in database/migrations, add columns that correspond to the CSV file’s structure. Here’s an example:

public function up()
{
    Schema::create('my_models', function (Blueprint $table) {
        $table->id();
        $table->string('column1');
        $table->string('column2');
       // Add more columns as needed
    });
}

Run the migration to create the table in your database:

php artisan migrate

Step 3: Preparing Your CSV File for Import

Before importing, ensure your CSV file is formatted correctly. It should match the structure of the database table. Additionally, place the CSV file in the Laravel project, for example, in the database/csv directory.

Example:

column1,column2,column3
data1-1,data1-2,data1-3
data2-1,data2-2,data2-3
data3-1,data3-2,data3-3
data4-1,data4-2,data4-3
data5-1,data5-2,data5-3

Step 4: Creating a Seeder to Import the CSV Data

Laravel utilizes seeders to populate database tables with data. You can create a seeder specifically for importing your CSV data:

php artisan make:seeder CsvImportSeeder

Edit the newly created seeder file in database/seeders. Utilize Laravel’s built-in methods and PHP’s native fgetcsv function to read and import the CSV file. See the example below:

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use League\Csv\Reader;

class CsvImportSeeder extends Seeder
{
    public function run()
    {
        $csv = Reader::createFromPath(database_path() . '/csv/yourfile.csv', 'r');
        $csv->setHeaderOffset(0); //set the CSV header offset

        foreach ($csv as $record) {
            DB::table('my_models')->insert([
                'column1' => $record['column1'],
                'column2' => $record['column2'],
                // Map other columns accordingly
            ]);
        }
    }
}

Note: This example uses the league/csv package for CSV handling, demonstrating a more advanced approach. To use league/csv, you must install it via Composer:

composer require league/csv

Step 5: Running the Seeder

Finally, you can run the seeder to import the data into your database:

php artisan db:seed --class=CsvImportSeeder

Conclusion

By following the steps above, you’ve successfully imported a CSV file into a MySQL database using Laravel. This guide introduced you to creating and running migrations, models, and seeders within the Laravel framework. Whether you’re working on a large-scale project or a simple application, mastering these techniques is crucial for efficiently managing database operations.

Remember, Laravel offers a wealth of features and tools to streamline your development process. Exploring further into Laravel’s documentation can open up even more possibilities, enhancing your capability to create robust, scalable web applications.

Next Article: Laravel: How to create custom Faker providers

Previous Article: Laravel: Rendering CSV data in an HTML table

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array