Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Eloquent Incrementable Laravel Package

testmonitor/eloquent-incrementable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require testmonitor/eloquent-incrementable
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        TestMonitor\Incrementable\IncrementableServiceProvider::class,
    ],
    
  2. First Use Case: Define an Incrementable trait in your Eloquent model:

    use TestMonitor\Incrementable\Incrementable;
    
    class Bug extends Model
    {
        use Incrementable;
    
        protected $incrementable = [
            'field' => 'code', // Custom auto-increment field
            'group_by' => 'project_id', // Reset counter per project_id
        ];
    }
    

    Now, Bug::create() will auto-generate sequential code values per project_id.


Implementation Patterns

Core Workflows

  1. Basic Incrementation:

    // Auto-increments 'code' per 'project_id'
    $bug = Bug::create(['project_id' => 1, 'title' => 'Fix login']);
    // $bug->code = 1 (for project_id=1)
    
  2. Manual Incrementation:

    // Force a specific value (bypasses auto-increment)
    $bug = Bug::create(['project_id' => 1, 'code' => 99, 'title' => 'Manual']);
    
  3. Group-Based Logic:

    // Reset counter for a group (e.g., after bulk deletes)
    Bug::where('project_id', 1)->resetIncrement();
    

Integration Tips

  • Migrations: Ensure your code field is nullable and has no default value:
    $table->integer('code')->nullable()->comment('Auto-incremented per project');
    
  • APIs: Use incrementable:generate to pre-generate codes for bulk inserts:
    $bugs = collect([...])->map(fn($data) => [
        ...$data,
        'code' => Bug::generateIncrement('project_id' => $data['project_id']),
    ]);
    
  • Validation: Add rules to enforce uniqueness per group:
    use Illuminate\Validation\Rule;
    
    $validator->rule('code', Rule::unique('bugs')->where('project_id', $data['project_id']));
    

Gotchas and Tips

Pitfalls

  1. Race Conditions:

    • Auto-increment logic runs in PHP, not the DB. Use transactions for bulk operations:
      DB::transaction(function () {
          Bug::create([...]);
          Bug::create([...]);
      });
      
    • For high-concurrency apps, consider adding a lock field or using database-level sequences as a fallback.
  2. Group Changes:

    • Changing group_by after data exists will break increment sequences. Document this in your schema.
  3. Soft Deletes:

    • The package doesn’t handle soft deletes by default. Override getIncrementableKey() to exclude soft-deleted records:
      protected function getIncrementableKey()
      {
          return $this->fresh()->group_by . '|' . ($this->deleted_at ? 'deleted' : 'active');
      }
      

Debugging

  • Log Increment Values: Enable debug mode in config/incrementable.php:

    'debug' => env('INCREMENTABLE_DEBUG', false),
    

    Logs will show generated values and group queries.

  • Manual Overrides: If increments fail, manually set the field and bypass auto-generation:

    $bug = new Bug(['project_id' => 1, 'code' => null]);
    $bug->forceFill(['code' => 5])->save();
    

Extension Points

  1. Custom Generators: Override generateIncrement() for non-sequential logic (e.g., UUIDs):

    protected function generateIncrement($attributes)
    {
        return Str::upper(Str::random(6));
    }
    
  2. Dynamic Groups: Use closures for runtime group determination:

    protected $incrementable = [
        'field' => 'ticket',
        'group_by' => function ($model) {
            return $model->project_id . '-' . $model->priority;
        },
    ];
    
  3. Event Hooks: Listen for incrementable.generated events to log or audit increments:

    Bug::incrementableGenerated(function ($model, $value) {
        \Log::info("Generated {$model->field}={$value} for group {$model->group_by}");
    });
    

Config Quirks

  • Cache: The package caches increment counts per group. Clear cache with:

    \TestMonitor\Incrementable\Incrementable::clearCache();
    

    Or disable caching in config/incrementable.php:

    'cache' => false,
    
  • Field Types: Supports integers, strings, and UUIDs. For strings, ensure your DB column matches (e.g., VARCHAR(255)).

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope