Skip to content

Instantly share code, notes, and snippets.

@dillingham
Last active November 12, 2021 10:10
Show Gist options
  • Save dillingham/94659955fbc32d2a68d0c503dfab98ac to your computer and use it in GitHub Desktop.
Save dillingham/94659955fbc32d2a68d0c503dfab98ac to your computer and use it in GitHub Desktop.
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);
    });
}

The new base seeder class

<?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;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment