Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FabioPacifici's avatar

Import CSV files into dB, Laravel 5.7

Hello all! how are you doing today? I would like to import information from a CSV file and store them inside a dedicated DB table. Then present the results inside a chart using charts.js. What would be the best and cleanest approach to achieve that today using Laravel 5.7, Vue and chart.js?

Thanks in advance

0 likes
6 replies
danyal14's avatar

Laravel provides Storage option, could be public or private location. I assume that, file you need to import is private, you can follow the steps.

Step1: From controller get file uploaded via front end & store in private folder named 'upload_private'

    $fileOriginalName = $request->file->getClientOriginalName();
        $filename = $request->file->storeAs('upload_private', $originalName);

Now file is stored, you can parse it

        $rows= explode(PHP_EOL, Storage::get($filename));
       foreach ($rows as $row)
        {
            $record = str_getcsv($row);
        // and do your processing here...

    }
Theo1's avatar

$file = $request->file('file');

     if (($handle = fopen ( $file->getPathname(), 'r' )) !== FALSE) {

    while ( ($data = fgetcsv ( $handle,1000, delimiter/separator )) !== FALSE ) {

     
        
       //Do something with data here

    }
    fclose ( $handle );
}
FabioPacifici's avatar
FabioPacifici
OP
Best Answer
Level 12

Thank you all for your replies!

@talinon thanks for your tip! I managed to make it work using Laravel-Excel but I had to install some of the required libraries first.

So finally the csv file is imported like so:

The table schema

 Schema::create('speed_tests', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('server_id');
            $table->text('sponsor');
            $table->text('server_name');
            $table->text('timestamp');
            $table->decimal('distance');
            $table->integer('ping');
            $table->bigInteger('download');
            $table->bigInteger('upload');
            $table->text('share')->nullable();
            $table->ipAddress('ip_address');
            $table->timestamps();

The Laravel-Excel import class

<?php

namespace App\Imports;
use App\SpeedTest;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
use Maatwebsite\Excel\Concerns\ToModel;

class SpeedTestsImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new SpeedTest([
            'server_id'     => $row[0],
            'sponsor'       => $row[1], 
            'server_name'   => $row[2],
            'timestamp'     => $row[3],
            'distance'      => $row[4], 
            'ping'          => $row[5],
            'download'      => $row[6],
            'upload'        => $row[7],
            'share'         => $row[8],
            'ip_address'    => $row[9]
        ]);
    }
}

Inside the controller:

    public function import() 
    {
        Excel::import(new SpeedTestsImport, 'test.csv');

        return redirect('/')->with('success', 'All good!');
    }

And tested in my routes file

Route::get('/import', 'SpeedTestController@import');

ettore's avatar

How i would solve this, loading a CSV directly into the database, works like a charm

$query = sprintf("LOAD DATA INFILE '%s'
        IGNORE INTO TABLE {$this->table_name()}
        CHARACTER SET utf8
        FIELDS TERMINATED BY '{$this->terminated_by()}'
        ENCLOSED BY '\"'
        ESCAPED BY ''
        LINES TERMINATED BY '\n'
        IGNORE 1 ROWS", addslashes($this->importfile_path));
        \DB::connection()->getpdo()->exec($query);

Please or to participate in this conversation.