1. Go to this page and download the library: Download yavor-ivanov/csv-importer library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use YavorIvanov\CsvImporter\CSVImporter;
class UserRolesImporter extends CSVImporter
{
// Defualt name for the CSV to import.
public $file = 'user_roles.csv';
// Eloquent model name to create/update (case sensitive)
protected $model = 'UserRole';
// Maps an id field in the csv to a database id field. Format ['csv_column_name' => 'db_column_name']
protected $primary_key = ['id' => 'csv_id'];
// Maps an id field in the csv to a database id field. Format ['csv_column_name' => 'db_column_name']
protected $cache_key = ['id' => 'csv_id'];
protected function update($row, $o)
{
$o->csv_id = $row['id'];
$o->role_name = $row['role_name'];
$o->save();
}
protected function import_row($row)
{
return UserRole::create([
'role_name' => $row['role_name'],
'csv_id' => $row['id'],
]);
}
}
protected function get_validators()
{
return [
'unique' => function ($col, $row)
{
$val = $row[$col];
$current_obj = $this->get_from_cache($row);
$model_col = array_get($this->column_mapping, "$col.name", $col);
$occurrences = $this->cache->reduce(function($carry, $o) use ($current_obj, $model_col, $val) {
if ($o != $current_obj && strtolower($o->$model_col) == strtolower($val))
return $carry + 1;
return $carry;
}, 0);
if ($occurrences > 0)
{
Log::error("A $this->name with $col = $val already exists in $this->file.");
die;
}
},
];
}
protected function pivot_row($row)
{
$pivoted_row = [];
$book_id = $row['book'];
// Loops over the genre columns only, as there is only one book column.
foreach (array_filter(array_slice($row, 1)) as $genre_id)
{
array_push($pivoted_row, [
'book_id' => $book_id,
'genre_id' => $genre_id,
]);
}
return $pivoted_row;
}
use YavorIvanov\CsvImporter\CSVExporter;
class UserRolesImporter extends CSVExporter
{
// Defualt name for the CSV to export.
public $file = 'user_roles.csv';
// Eloquent model to select from (case sensitive)
protected $model = 'UserRole';
protected $column_mapping = [
'csv_id' => 'id',
'role_name',
];
}