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

Audit Request Bundle Laravel Package

dmp/audit-request-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dmp/audit-request-bundle
    

    Register the bundle in config/app.php under providers:

    Dmp\AuditRequestBundle\AuditRequestBundle::class,
    
  2. First Use Case Annotate a controller method to log audit requests:

    use Dmp\AuditRequestBundle\Annotation\AuditableRequest;
    
    class UserController extends Controller
    {
        #[AuditableRequest(referenceType: 'user', referenceIdentifier: 'user_id')]
        public function update(Request $request, $user_id)
        {
            // Your logic here
        }
    }
    
  3. Configuration Check config/audit_request.php for default settings (e.g., storage driver, log format). Override as needed:

    'storage' => [
        'driver' => 'database', // or 'log', 'custom'
        'table' => 'audit_requests',
    ],
    
  4. Verify Trigger the annotated endpoint and inspect the configured storage (e.g., audit_requests table or Laravel logs).


Implementation Patterns

Common Workflows

1. Logging Requests with Dynamic References

Use dynamic values for referenceIdentifier via closures:

#[AuditableRequest(
    referenceType: 'order',
    referenceIdentifier: fn(Request $request) => $request->route('order_id')
)]
public function processOrder(Request $request)
{
    // ...
}

2. Conditional Auditing

Skip auditing for specific cases (e.g., admin users):

#[AuditableRequest(referenceType: 'post', referenceIdentifier: 'post_id')]
public function delete(Request $request, $post_id)
{
    if ($request->user()->isAdmin()) {
        return response()->json(['message' => 'Skipped audit for admin']);
    }
    // Audit will run automatically
}

3. Custom Storage Drivers

Extend the bundle to support custom storage (e.g., Elasticsearch):

// config/audit_request.php
'storage' => [
    'driver' => 'custom',
    'handler' => \App\Services\AuditHandler::class,
],

Implement Dmp\AuditRequestBundle\Contracts\AuditHandlerInterface.

4. Middleware Integration

Use the bundle’s middleware to audit requests globally:

// app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        // ...
        \Dmp\AuditRequestBundle\Http\Middleware\AuditRequestMiddleware::class,
    ],
];

5. Batch Processing

For bulk operations (e.g., API imports), audit at the start/end:

#[AuditableRequest(referenceType: 'import', referenceIdentifier: 'batch_123')]
public function import(Request $request)
{
    // Process bulk data...
    AuditRequest::log('import_completed', ['status' => 'success']);
}

Integration Tips

  • Laravel Events: Trigger custom events post-audit:
    event(new AuditLogged($auditData));
    
  • Validation: Combine with Laravel’s validation to ensure referenceIdentifier is valid before auditing.
  • Testing: Mock the AuditHandler in tests:
    $this->app->instance(
        \Dmp\AuditRequestBundle\Contracts\AuditHandlerInterface::class,
        Mockery::mock()
    );
    

Gotchas and Tips

Pitfalls

  1. Annotation Caching

    • Clear Laravel’s annotation cache after adding new attributes:
      php artisan cache:clear
      
    • Or use #[AuditableRequest] on classes (not just methods) if caching issues persist.
  2. Circular Dependencies

    • Avoid circular references in referenceIdentifier closures (e.g., calling the same method recursively).
  3. Database Schema Mismatch

    • If using the database driver, ensure the audit_requests table exists. Run:
      php artisan vendor:publish --provider="Dmp\AuditRequestBundle\AuditRequestBundle" --tag="migrations"
      php artisan migrate
      
  4. Performance Overhead

    • Auditing adds I/O operations. Disable for high-frequency, low-value endpoints:
      #[AuditableRequest(enabled: false)]
      
  5. Reference Identifier Serialization

    • Complex objects (e.g., arrays) in referenceIdentifier may not serialize well. Use strings or simple types.

Debugging

  • Log Output: Enable debug mode in config/audit_request.php:

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

    Logs will appear in storage/logs/laravel.log.

  • Middleware Debugging: Temporarily disable the middleware to isolate issues:

    // app/Http/Kernel.php
    'web' => [
        // \Dmp\AuditRequestBundle\Http\Middleware\AuditRequestMiddleware::class,
    ],
    

Extension Points

  1. Custom Attributes Extend the annotation to support additional fields:

    #[AuditableRequest(
        referenceType: 'user',
        referenceIdentifier: '123',
        metadata: ['action' => 'update', 'ip' => $request->ip()]
    )]
    
  2. Pre/Post Audit Hooks Bind to the audit.request event in EventServiceProvider:

    protected $listen = [
        'Dmp\AuditRequestBundle\Events\AuditRequestEvent' => [
            \App\Listeners\LogAuditToExternalService::class,
        ],
    ];
    
  3. Dynamic Reference Types Override the getReferenceType() method in a custom handler to compute types dynamically.

  4. Rate Limiting Combine with Laravel’s rate limiting to prevent audit log spam:

    Route::middleware(['throttle:60,1'])->group(function () {
        // Auditable routes
    });
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware