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 Revert Query Laravel Package

djunehor/laravel-revert-query

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require djunehor/laravel-revert-query
    

    Publish the migration and config:

    php artisan vendor:publish --provider="Djunehor\RevertQuery\RevertQueryServiceProvider"
    php artisan migrate
    
  2. Enable Logging for a Model: Add the Revertable trait to your model:

    use Djunehor\RevertQuery\Traits\Revertable;
    
    class User extends Model
    {
        use Revertable;
    }
    
  3. First Use Case: Trigger an event (e.g., create, update, delete) on a model, then inspect the logs via:

    // View all logs for a model
    $logs = \Djunehor\RevertQuery\Facades\RevertQuery::logs('App\User', 1);
    
    // Revert a specific log entry
    $log = $logs->first();
    $log->revert();
    

Implementation Patterns

Core Workflows

  1. Logging Events Automatically: The package hooks into Laravel’s model events (creating, created, updating, updated, deleting, deleted). No manual logging required—just use the Revertable trait.

  2. Querying Logs: Use the facade to fetch logs for a model:

    // Get logs for a specific model instance
    $logs = \Djunehor\RevertQuery\Facades\RevertQuery::logs('App\User', $userId);
    
    // Filter by event type (e.g., 'update')
    $updateLogs = $logs->where('event', 'update');
    
  3. Reverting Changes: Revert a log entry to its previous state:

    $log = \Djunehor\RevertQuery\Facades\RevertQuery::logs('App\User', 1)->first();
    $log->revert(); // Reverts the model to the state recorded in the log
    
  4. Soft Deletes: If your model uses soft deletes, ensure the Revertable trait is applied after SoftDeletes in the use statement to avoid conflicts.

Integration Tips

  • Custom Events: Extend the package to log custom events by publishing the config and adding your event names to config/revert-query.php under events.

    'events' => [
        'creating', 'created', 'updating', 'updated', 'deleting', 'deleted', 'custom_event',
    ],
    
  • Middleware for Admin Actions: Use middleware to restrict revert capabilities to admin users:

    public function handle($request, Closure $next)
    {
        if ($request->user()->isAdmin()) {
            return $next($request);
        }
        abort(403);
    }
    
  • Batch Reverts: Revert multiple logs in a transaction for consistency:

    \DB::transaction(function () {
        $logs = \Djunehor\RevertQuery\Facades\RevertQuery::logs('App\User', 1)->limit(5);
        foreach ($logs as $log) {
            $log->revert();
        }
    });
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Logging every model event can bloat your database. Use selectively (e.g., only for critical models like User or Order).
    • Mitigation: Disable logging for non-critical models by excluding them from the Revertable trait or using the ignoreEvents config option.
  2. Soft Deletes Conflicts:

    • If a model is soft-deleted, reverting a log might restore it unexpectedly. Ensure your business logic accounts for this.
    • Fix: Add a check before reverting:
      if (!$model->trashed) {
          $log->revert();
      }
      
  3. Event Ordering:

    • The package logs events in the order they occur. Reverting out-of-order logs (e.g., reverting a delete before an update) may cause inconsistencies.
    • Tip: Always revert logs in chronological order (oldest first).
  4. Large Log Volumes:

    • Reverting thousands of logs can time out or lock tables. Use batch processing or queue the reverts:
      foreach ($logs->chunk(100) as $chunk) {
          RevertJob::dispatch($chunk);
      }
      

Debugging

  • Missing Logs:

    • Verify the Revertable trait is applied to the model.
    • Check if the revert_query table exists and has data:
      php artisan tinker
      >> \Djunehor\RevertQuery\Models\RevertQueryLog::count();
      
    • Ensure no exceptions are silently failing during event firing (check Laravel logs).
  • Revert Failures:

    • If a revert throws an exception, inspect the old_data and new_data fields in the log to debug the state mismatch.
    • Enable debug mode in config/revert-query.php:
      'debug' => env('REVERT_QUERY_DEBUG', false),
      

Extension Points

  1. Custom Storage: Override the default log storage (e.g., switch to Redis) by binding a custom repository:

    $this->app->bind(
        \Djunehor\RevertQuery\Repositories\RevertQueryRepository::class,
        \App\Repositories\CustomRevertQueryRepository::class
    );
    
  2. Event Payloads: Extend the logged data by overriding the getRevertableAttributes method in your model:

    protected function getRevertableAttributes()
    {
        return array_merge(parent::getRevertableAttributes(), ['custom_field']);
    }
    
  3. Web Interface: Build a simple admin panel to view/revert logs using Laravel’s built-in tools:

    // routes/web.php
    Route::get('/revert-logs', [RevertLogController::class, 'index']);
    
    // app/Http/Controllers/RevertLogController.php
    public function index()
    {
        $logs = \Djunehor\RevertQuery\Facades\RevertQuery::all();
        return view('revert-logs.index', compact('logs'));
    }
    
  4. Event Filtering: Exclude specific models or events from logging via config:

    'ignore_models' => [
        'App\LogEntry',
        'App\CacheClearer',
    ],
    'ignore_events' => [
        'deleted', // Skip soft deletes
    ],
    
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.
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
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