public function run()
{
DB::disableQueryLog();
DB::table('products')->truncate();
$this->csv('products.csv', function ($row) {
$brand = $this->cell([
'class' => Brand::class,
'column' => 'title',
'value' => $row['brand'],
]);
$productLine = $this->cell([
'class' => ProductLine::class,
'column' => 'title',
'value' => $row['product_line'],
'extra' => [
'brand_id' => $brand->id,
],
]);
unset($row['brand']);
unset($row['product_line']);
Product::factory()
->for($brand)
->for($productLine)
->create($row);
});
}
<?php
namespace Database\Seeders;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder as BaseSeeder;
class Seeder extends BaseSeeder
{
public function csv(string $filename, callable $callable): void
{
$rows = [];
$file = fopen(__DIR__."/csv/$filename", 'r');
while (($line = fgetcsv($file)) !== false) {
$rows[] = $line;
}
fclose($file);
$keys = array_shift($rows);
foreach ($rows as $i => $row) {
$rows[$i] = array_combine($keys, $row);
}
foreach ($rows as $row) {
$callable($row);
}
}
public function cell(array $settings):Model
{
$class = $settings['class'];
$value = $settings['value'];
$extra = $settings['extra'] ?? [];
$column = $settings['column'];
$payload = array_merge([$column => $value], $extra);
$model = app($class)->firstWhere($payload);
if (! $model) {
$model = app($class)->factory()->create($payload);
}
return $model;
}
}