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

Laravel Eloquent Sequencer Laravel Package

gurgentil/laravel-eloquent-sequencer

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require gurgentil/laravel-eloquent-sequencer
    php artisan vendor:publish --provider="Gurgentil\LaravelEloquentSequencer\LaravelEloquentSequencerServiceProvider"
    

    Publish the config file to customize defaults (column name, initial value, strategy).

  2. Model Setup: Add $sequenceable = true; to your Eloquent model class. Example:

    use Gurgentil\LaravelEloquentSequencer\Traits\Sequenceable;
    
    class Post extends Model
    {
        use Sequenceable;
        // ...
    }
    
  3. First Use Case: Save a new model instance—it will automatically assign a sequence value (default: position column, starting at 1).

    $post = new Post(['title' => 'First Post']);
    $post->save(); // Auto-assigns `position = 1`
    

Where to Look First

  • Config File: config/eloquentsequencer.php for global settings.
  • Traits: Sequenceable trait in Traits/Sequenceable.php for customization hooks.
  • Migrations: Check if your table has the sequence column (default: position).

Implementation Patterns

Core Workflows

  1. Basic Sequencing:

    • Enable sequencing via $sequenceable = true; in the model.
    • Use strategy: 'always' to sequence on every save()/update().
    • Use strategy: 'on_create' to sequence only during initial creation.
  2. Custom Column/Initial Value: Override defaults in the model:

    class Post extends Model
    {
        use Sequenceable;
    
        protected $sequenceColumn = 'order';
        protected $sequenceInitialValue = 100;
    }
    
  3. Manual Sequencing: Trigger sequencing manually:

    $post->sequence(); // Assigns next value in sequence
    
  4. Bulk Operations: Use sequenceMany() for batch inserts:

    Post::sequenceMany([['title' => 'Post 1'], ['title' => 'Post 2']]);
    
  5. Integration with Events: Listen to sequenced events for post-sequencing logic:

    Post::created(function ($post) {
        if ($post->wasRecentlyCreated) {
            // Handle new sequence assignment
        }
    });
    

Advanced Patterns

  1. Dynamic Sequences: Override getNextSequenceValue() to generate values dynamically:

    protected function getNextSequenceValue()
    {
        return Carbon::now()->timestamp;
    }
    
  2. Conditional Sequencing: Use shouldSequence() to control when sequencing occurs:

    protected function shouldSequence()
    {
        return $this->isPublished();
    }
    
  3. Soft Deletes + Sequencing: Re-sequence after soft deletes to fill gaps:

    Post::withTrashed()->orderBy('position')->get();
    
  4. API Responses: Include sequence values in API responses:

    return PostResource::collection(Post::latest()->get());
    

Gotchas and Tips

Pitfalls

  1. Column Mismatch:

    • Ensure your database table has the sequence column (default: position).
    • Fix: Run a migration or update the $sequenceColumn in the model.
  2. Race Conditions:

    • Concurrent save() calls may overwrite sequences if using strategy: 'always'.
    • Fix: Use strategy: 'on_create' or implement optimistic locking.
  3. Initial Value Conflicts:

    • Starting at 1 may cause issues if records exist with manual position values.
    • Fix: Set sequenceInitialValue higher (e.g., 1000) or use DB::transaction() to reset sequences.
  4. Soft Deletes:

    • Soft-deleted records retain their sequence values, which may cause gaps.
    • Fix: Re-sequence after bulk deletes or use forceDelete().
  5. Caching:

    • Next sequence values may be cached aggressively. Clear cache if sequences appear stale:
    php artisan cache:clear
    

Debugging Tips

  1. Log Sequencing: Enable debug mode in config:

    'debug' => true,
    

    Check logs for sequencing events.

  2. Check Next Value: Inspect the raw SQL for sequence queries:

    \DB::enableQueryLog();
    $post->sequence();
    dd(\DB::getQueryLog());
    
  3. Test Edge Cases:

    • Test with concurrent requests.
    • Verify behavior after soft deletes/restores.

Extension Points

  1. Custom Strategies: Extend the Strategy class to add new sequencing logic (e.g., "gap-fill" for soft deletes).

  2. Hooks: Override these methods in your model:

    • getNextSequenceValue(): Custom value logic.
    • shouldSequence(): Conditional sequencing.
    • sequenced(): Post-sequencing actions.
  3. Database-Agnostic: The package uses raw queries for sequence management. For complex setups, override:

    protected function getNextSequenceQuery()
    {
        return DB::table($this->getTable())
            ->where($this->sequenceColumn, '>', $this->{$this->sequenceColumn})
            ->min($this->sequenceColumn);
    }
    
  4. Batch Optimization: For large datasets, use chunking:

    Post::chunk(100, function ($posts) {
        foreach ($posts as $post) {
            $post->sequence();
            $post->save();
        }
    });
    

Config Quirks

  • Strategy Priority: always > on_create > on_update > never.
  • Initial Value: Must be an integer. Non-integer values may cause errors.
  • Column Name: Must match the database column exactly (case-sensitive in some DBs).
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver