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 Nestedupdater Laravel Package

czim/laravel-nestedupdater

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require czim/laravel-nestedupdater
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Czim\NestedUpdater\NestedUpdaterServiceProvider"
    
  2. Basic Usage:

    use Czim\NestedUpdater\Facades\NestedUpdater;
    
    $post = Post::find(1);
    $data = [
        'title' => 'Updated Title',
        'comments' => [
            17, // Keep existing comment with ID 17
            ['id' => 18, 'body' => 'Updated'], // Update existing comment
            ['body' => 'New comment'] // Create new comment
        ]
    ];
    
    NestedUpdater::update($post, $data);
    
  3. First Use Case:

    • Updating a parent model (e.g., Post) with nested relations (e.g., comments, tags, authors).
    • Example: A CMS where admins edit blog posts with inline comments, tags, and user metadata.

Implementation Patterns

Core Workflow

  1. Define Relationships: Ensure your model uses standard Eloquent relationships (e.g., hasMany, belongsToMany).

    class Post extends Model {
        public function comments() { return $this->hasMany(Comment::class); }
        public function tags() { return $this->belongsToMany(Tag::class); }
    }
    
  2. Update Structure: Pass an array where:

    • Top-level keys = model attributes or relation names.
    • Relation values = Array of IDs (keep), associative arrays (update/create), or null (delete).
      $data = [
          'title' => 'New Title',
          'comments' => [1, 2, ['body' => 'New'], null], // Keep 1,2; update new; delete null
          'tags' => [1, 3, 5] // Sync tags (add/remove)
      ];
      
  3. Bulk Operations: Use updateMany() for multiple models:

    $posts = Post::where('published', false)->get();
    NestedUpdater::updateMany($posts, $data);
    
  4. Custom Callbacks: Attach callbacks for pre/post-update logic:

    NestedUpdater::update($post, $data, function ($model, $relation, $data) {
        if ($relation === 'comments') {
            // Custom logic for comments
        }
    });
    

Integration Tips

  • APIs: Ideal for nested PATCH/PUT requests (e.g., /posts/1 with comments payload).
  • Forms: Use with Laravel Collective or Livewire for dynamic nested inputs.
  • Validation: Combine with Laravel’s validation (e.g., Validator::make($data, [...])).
  • Events: Listen to updating/updated events for side effects (e.g., notifications).

Gotchas and Tips

Pitfalls

  1. Circular References: Avoid infinite loops if relations reference each other (e.g., PostAuthorPost). Fix: Explicitly exclude problematic relations in config:

    'exclude_relations' => ['authors.posts'],
    
  2. Mass Assignment: Ensure nested models have $fillable set or use updateOrCreate with guarded attributes. Fix: Whitelist attributes in config:

    'allowed_attributes' => ['comments.*' => ['body', 'status']],
    
  3. Performance: Deeply nested updates may trigger N+1 queries. Fix: Use with() to eager-load relations:

    $post = Post::with('comments.author')->find(1);
    
  4. ID Conflicts: Passing duplicate IDs (e.g., [1, 1, 2]) may cause unexpected behavior. Fix: Normalize input arrays or use array_unique().

Debugging

  • Log Updates: Enable debug mode in config:

    'debug' => true,
    

    Logs will show executed queries and skipped operations.

  • Dry Run: Use NestedUpdater::dryRun($model, $data) to preview changes without saving.

Extension Points

  1. Custom Updaters: Override the default updater for specific relations:

    NestedUpdater::extend('comments', function ($model, $relation, $data) {
        // Custom logic for comments
    });
    
  2. Model Events: Trigger events for nested updates:

    NestedUpdater::onUpdating(function ($model, $data) {
        event(new NestedUpdateStarting($model, $data));
    });
    
  3. Conditional Updates: Skip updates based on conditions:

    NestedUpdater::update($post, $data, function ($model, $relation, $data) {
        if ($relation === 'tags' && !$model->isAdmin) {
            return false; // Skip tags for non-admins
        }
    });
    
  4. Soft Deletes: Configure soft-delete behavior for nested models:

    'soft_deletes' => [
        'comments' => true, // Soft delete instead of hard delete
    ],
    
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