laravel csv seeder for pivots tables
Example of csv file:
name,email,roles
teste,teste@example.com,"editor,vip"
teste2,teste2@example.com,"admin"
Example how to Override seedFromCSV method to attach roles to user .
<?php
namespace Database\Seeders;
use App\Models\Site;
use Flynsarmy\CsvSeeder\CsvSeeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class SiteSeeder extends CsvSeeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function __construct()
{
$this->table = 'users';
$this->filename = base_path() . '/database/seeders/csvs/users.csv';
$this->mapping = [0 => 'name', 1 => 'email', 5 => 'roles'];
$this->insert_chunk_size = 1;
$this->offset_rows = 1;
$this->timestamps = false;
}
public function run()
{
// Recommended when importing larger CSVs
DB::disableQueryLog();
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
// Uncomment the below to wipe the table clean before populating
DB::table($this->table)->truncate();
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
parent::run();
}
/**
* Override seedFromCSV method
*/
public function insert(array $seedData): bool
{
try {
$user = $seedData[0];
$roles= $user['roles'];
unset($user['roles']);
$user_id= DB::connection($this->connection)->table($this->table)->insertGetId($user);
$roles= explode(',', $roles);
if(!empty($roles)){
$rolesIds = [];
foreach ($roles as $name) {
$role = DB::table("roles")->where('name', trim($name))->first();
if($role){
$rolesIds[] = $role->id;
}
}
User::find($user_id)->roles()->attach($rolesIds);
}
} catch (\Exception $e) {
Log::error("CSV insert failed: " . $e->getMessage() . " - CSV " . $this->filename);
return false;
}
return true;
}
}