1
0
Fork 0
BitHarbor/backend/database/seeders/CategorySeeder.php
2026-04-29 15:35:06 +02:00

81 lines
2.1 KiB
PHP

<?php
namespace Database\Seeders;
use App\Models\Category;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class CategorySeeder extends Seeder
{
use WithoutModelEvents;
public function run(): void
{
$categories = [
'Computers' => [
'Laptop',
'Stationary',
'Server'
],
'Components' => [
'Memory',
'Harddrives' => [
'SSD',
'Mechanical',
],
'Motherboard',
'Graphicscard',
'Soundcard',
'Tools'
],
'Accessories' => [
'Keyboard',
'Mouse',
'Bags',
'Streaming'
],
'Monitor' => [
'Gaming monitors',
'Mounting',
'Accessories'
],
];
$this->seedCategoryTree($categories);
}
/**
* @param array<int|string, mixed> $nodes
*/
private function seedCategoryTree(array $nodes, ?int $parentId = null, string $pathPrefix = ''): void
{
$sortOrder = 0;
foreach ($nodes as $key => $value) {
$name = is_int($key) ? (string) $value : (string) $key;
$children = is_int($key) ? [] : (is_array($value) ? $value : []);
$path = trim($pathPrefix.' '.$name);
$slug = Str::slug($path);
$category = Category::query()->updateOrCreate(
['slug' => $slug],
[
'parent_id' => $parentId,
'name' => $name,
'description' => null,
'active' => true,
'sort_order' => $sortOrder,
],
);
if ($children !== []) {
$this->seedCategoryTree($children, (int) $category->id, $path);
}
$sortOrder++;
}
}
}