定制 marwen-brini/smart-seeder 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

marwen-brini/smart-seeder

最新稳定版本:v1.0.0

Composer 安装命令:

composer require marwen-brini/smart-seeder

包简介

This is my package smart-seeder

README 文档

README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Safe, intelligent database seeding for Laravel with preview capabilities, idempotent operations, environment awareness, and full rollback support.

Features

  • Preview before execution - See exactly what will happen with seed:plan
  • Idempotent operations - Run seeders multiple times safely
  • Multiple seeding modes - upsert, insert_ignore, insert_only, update_only, sync
  • Validation support - Validate records before insertion
  • Dependency resolution - Automatically run seeders in the correct order
  • Rollback support - Undo seeder operations with seed:undo
  • AutoFaker - Smart fake data generation based on field names
  • Laravel Factory support - Use existing factories in seeders
  • Lifecycle hooks - Run custom logic after insert/update operations
  • Data transformation - Transform and mutate records before insertion
  • History tracking - Track all seeder executions

Requirements

  • PHP ^8.3 || ^8.4
  • Laravel ^11.0 || ^12.0

Installation

composer require marwen-brini/smart-seeder --dev

Publish and run the migrations for history tracking:

php artisan vendor:publish --tag="smart-seeder-migrations"
php artisan migrate

Optionally publish the config file:

php artisan vendor:publish --tag="smart-seeder-config"

Quick Start

Create a Seeder

php artisan seed:make ProductsSeeder

Define Your Seeder

<?php

namespace Database\Seeders;

use Filler\Filler;

class ProductsSeeder extends Filler
{
    protected array $uniqueBy = ['sku'];
    protected string $mode = 'upsert';

    public function table(): string
    {
        return 'products';
    }

    public function data(): array
    {
        return [
            ['sku' => 'LAPTOP-001', 'name' => 'Laptop Pro', 'price' => 999.99],
            ['sku' => 'MOUSE-001', 'name' => 'Wireless Mouse', 'price' => 49.99],
        ];
    }
}

Preview Changes

php artisan seed:plan ProductsSeeder

Execute Safely

php artisan seed:safe ProductsSeeder

Seeding Modes

Mode Insert New Update Existing Delete Missing
upsert Yes Yes No
insert_ignore Yes No No
insert_only Yes Error No
update_only No Yes No
sync Yes Yes Yes

Data Generation

Manual Data

public function data(): array
{
    return [
        ['name' => 'Product 1', 'price' => 99.99],
        ['name' => 'Product 2', 'price' => 149.99],
    ];
}

AutoFaker

AutoFaker automatically detects field types and generates appropriate fake data:

public function data(): array
{
    return $this->fake(10, [
        'price' => fn($faker) => $faker->randomFloat(2, 10, 500),
    ]);
}

Laravel Factory

Use existing Laravel factories:

protected ?string $model = Product::class;

public function data(): array
{
    return [
        ...$this->factory(5),                    // 5 regular products
        ...$this->factory(3, ['premium']),       // 3 with state
        ...$this->factorySequence([              // specific values
            ['name' => 'Item A'],
            ['name' => 'Item B'],
        ]),
    ];
}

Validation

protected array $rules = [
    'name' => 'required|string|min:3',
    'price' => 'required|numeric|min:0',
    'email' => 'required|email',
];

protected string $onValidationError = 'skip'; // 'abort', 'skip', 'log'

Dependencies

Define seeder dependencies to ensure correct execution order:

protected array $dependencies = [
    CategoriesSeeder::class,
    BrandsSeeder::class,
];

Run with dependencies:

php artisan seed:safe ProductsSeeder --with-dependencies

Commands

seed:plan

Preview what a seeder will do:

php artisan seed:plan ProductsSeeder
php artisan seed:plan ProductsSeeder --limit=20

seed:safe

Execute a seeder safely:

php artisan seed:safe ProductsSeeder
php artisan seed:safe ProductsSeeder --force
php artisan seed:safe ProductsSeeder --with-dependencies
php artisan seed:safe ProductsSeeder --dry-run
php artisan seed:safe --all  # Run all Filler seeders

seed:undo

Rollback the last seeder execution:

php artisan seed:undo
php artisan seed:undo --seeder=ProductsSeeder
php artisan seed:undo --batch=5

seed:status

View seeder history:

php artisan seed:status
php artisan seed:status --limit=20

seed:make

Generate a new seeder:

php artisan seed:make ProductsSeeder
php artisan seed:make ProductsSeeder --table=products

Lifecycle Hooks

Run custom logic after records are inserted or updated:

protected function afterInsert(array $record, int $id): void
{
    // Called after each record is inserted
    // $id contains the auto-incremented ID
    cache()->forget('products_count');
}

protected function afterUpdate(array $record, object $existing): void
{
    // Called after each record is updated
    // $existing contains the original record before update
    Log::info("Product updated: {$existing->name}");
}

Data Transformation

Transform records before they are inserted:

protected function transform(array $record): array
{
    $record['slug'] = Str::slug($record['name']);
    return $record;
}

Use mutators for field-level transformations:

protected array $mutators = [
    'password' => 'hash',           // Hash passwords
    'email' => 'lowercase',         // Lowercase emails
    'name' => 'trim',               // Trim whitespace
];

Environment Awareness

Restrict seeders to specific environments:

protected array $environments = ['local', 'staging'];

Full Example

<?php

namespace Database\Seeders;

use App\Models\Product;
use Filler\Filler;

class ProductsSeeder extends Filler
{
    protected array $uniqueBy = ['sku'];
    protected string $mode = 'upsert';
    protected string $version = '2.0';
    protected ?string $model = Product::class;

    protected array $dependencies = [
        CategoriesSeeder::class,
    ];

    protected array $environments = ['local', 'staging'];

    protected array $rules = [
        'sku' => 'required|string',
        'name' => 'required|string|min:3',
        'price' => 'required|numeric|min:0',
    ];

    protected string $onValidationError = 'skip';

    public function table(): string
    {
        return 'products';
    }

    public function data(): array
    {
        return [
            // Manual data
            ['sku' => 'FEATURED-001', 'name' => 'Featured Product', 'price' => 299.99],

            // Factory generated
            ...$this->factory(10),

            // AutoFaker generated
            ...$this->fake(5, ['sku' => fn($f) => 'AUTO-' . $f->unique()->randomNumber(5)]),
        ];
    }
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

If you discover a security vulnerability, please send an email to marwen.brini@outlook.com. All security vulnerabilities will be promptly addressed.

Credits

License

The MIT License (MIT). Please see License File for more information.

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-15