Handy one liner to parse a CSV file into an array
<?php
$csv = array_map('str_getcsv', file('data.csv'));
?>
Nov 19, 2018
6
Level 12
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
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');
Please or to participate in this conversation.