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

Pd Activity Laravel Package

appaydin/pd-activity

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

Since this is a Symfony bundle, Laravel developers will need to adapt it via Symfony Bridge (symfony/http-foundation, symfony/mailer, etc.). Start by:

  1. Install Dependencies

    composer require appaydin/pd-activity symfony/http-foundation symfony/mailer symfony/messenger
    
  2. Configure Laravel to Use Symfony Components Add to config/app.php:

    'providers' => [
        // ...
        Symfony\Component\HttpFoundation\SymfonyFacadeServiceProvider::class,
    ],
    
  3. Register the Bundle (Symfony-style) Create a custom service provider (e.g., PdActivityServiceProvider) to load the bundle:

    use Pd\ActivityBundle\PdActivityBundle;
    
    class PdActivityServiceProvider extends ServiceProvider {
        public function register() {
            $this->app->register(PdActivityBundle::class);
        }
    }
    
  4. Set Up Doctrine ORM (Laravel Eloquent Alternative) Use Doctrine ORM alongside Laravel’s Eloquent or map entities via a custom repository layer. Example:

    // config/doctrine.yaml (if using Laravel Doctrine)
    doctrine:
        orm:
            resolve_target_entities:
                Pd\ActivityBundle\Entity\UserInterface: App\Models\User
    
  5. Configure Logging Create config/pd_activity.php:

    return [
        'log_mailer' => env('PD_ACTIVITY_LOG_MAILER', true),
        'log_request' => env('PD_ACTIVITY_LOG_REQUEST', true),
        'log_ajax_request' => env('PD_ACTIVITY_LOG_AJAX', false),
        'request_exclude_methods' => explode(',', env('PD_ACTIVITY_EXCLUDE_METHODS', '')),
        'request_match_uri' => env('PD_ACTIVITY_URI_PATTERN', '^/api'),
    ];
    
  6. First Use Case: Log HTTP Requests Inject the ActivityLogRepository into a controller or middleware:

    use Pd\ActivityBundle\Repository\ActivityLogRepository;
    
    public function index(ActivityLogRepository $activityLog) {
        $logs = $activityLog->getUserLogs(auth()->user());
        return view('logs', compact('logs'));
    }
    

Implementation Patterns

1. Middleware Integration for Request Logging

Leverage Laravel’s middleware to auto-log requests before Symfony’s bundle processes them. Example:

// app/Http/Middleware/LogActivity.php
public function handle($request, Closure $next) {
    $response = $next($request);

    // Manually trigger Symfony's logger if needed
    if (config('pd_activity.log_request')) {
        $logger = app()->make('pd_activity.logger');
        $logger->logRequest($request, auth()->user());
    }

    return $response;
}

Register in app/Http/Kernel.php:

protected $middleware = [
    // ...
    \App\Http\Middleware\LogActivity::class,
];

2. Mail Logging via Symfony Mailer

Extend Laravel’s Mailable to log emails via the bundle:

use Pd\ActivityBundle\Logger\MailLogger;

class SendWelcomeEmail implements ShouldQueue {
    public function handle() {
        Mail::to($user)->send(new WelcomeEmail($user));

        // Log via Symfony's MailLogger
        $mailLogger = app()->make(MailLogger::class);
        $mailLogger->logMail(
            $user,
            'Welcome Email',
            $this->user->email,
            ['subject' => 'Welcome', 'to' => 'Your App']
        );
    }
}

3. Customizing Log Storage

Override the default Doctrine repository to store logs in Laravel’s database:

// app/Repositories/CustomActivityLogRepository.php
use Pd\ActivityBundle\Repository\ActivityLogRepository as BaseRepository;

class CustomActivityLogRepository extends BaseRepository {
    public function getUserLogs($user) {
        return DB::table('activity_logs')->where('user_id', $user->id)->get();
    }
}

Bind it in AppServiceProvider:

$this->app->bind(
    ActivityLogRepository::class,
    CustomActivityLogRepository::class
);

4. Excluding Sensitive Endpoints

Use Laravel’s route middleware to exclude admin routes from logging:

Route::middleware(['web', 'exclude_activity_log'])->group(function () {
    Route::get('/admin', [AdminController::class, 'index']);
});

Create middleware:

public function handle($request, Closure $next) {
    if ($request->is('admin*') && config('pd_activity.log_request')) {
        config(['pd_activity.log_request' => false]);
    }
    return $next($request);
}

5. Real-Time Logs with Laravel Echo

Push logs to clients using Laravel Echo + Pusher:

// In your log controller
public function stream(ActivityLogRepository $activityLog) {
    return response()->stream(function () use ($activityLog) {
        $logs = $activityLog->getRecentLogs(10);
        echo json_encode($logs);
    });
}

Frontend (Vue/React):

Echo.channel('activity-logs')
    .listen('LogEvent', (data) => {
        console.log('New log:', data);
    });

Gotchas and Tips

1. Doctrine vs. Eloquent Conflicts

  • Issue: The bundle expects Doctrine ORM, but Laravel uses Eloquent. Fix: Use a hybrid approach:
    • Store logs in Laravel’s logs table or a custom table.
    • Create a Doctrine-compatible facade to bridge the gap:
      // app/Facades/DoctrineFacade.php
      use Illuminate\Support\Facades\DB;
      
      class DoctrineFacade {
          public static function find($entity, $id) {
              return DB::table($entity)->find($id);
          }
      }
      
    • Override Pd\ActivityBundle\Entity\ActivityLog to use Eloquent models.

2. Symfony Mailer vs. Laravel Mailer

  • Issue: The bundle uses Symfony’s Mailer, but Laravel’s Mail facade is different. Fix: Create a wrapper class:
    // app/Services/MailLoggerAdapter.php
    use Symfony\Component\Mailer\MailerInterface;
    
    class MailLoggerAdapter {
        public function logMail($user, $message, $to, $context) {
            // Convert Laravel's mail data to Symfony format
            $symfonyMail = (new Email())
                ->to($to)
                ->subject($context['subject'])
                ->html($message);
    
            $mailer = app()->make(MailerInterface::class);
            $mailer->send($symfonyMail);
    
            // Store in DB via Eloquent
            DB::table('mail_logs')->insert([
                'user_id' => $user->id,
                'to' => $to,
                'subject' => $context['subject'],
                'created_at' => now(),
            ]);
        }
    }
    

3. Performance Overhead

  • Issue: Logging every request/email may slow down production. Fix:
    • Use queue workers for async logging:
      $logJob = new LogActivityJob($request, auth()->user());
      dispatch($logJob);
      
    • Enable logging only in staging/production via config:
      'log_request' => app()->environment('production'),
      

4. URI Matching Quirks

  • Issue: request_match_uri regex may not work as expected in Laravel’s routing. Fix: Normalize URIs before matching:
    $requestUri = parse_url($request->getUri(), PHP_URL_PATH);
    if (preg_match(config('pd_activity.request_match_uri'), $requestUri)) {
        // Log the request
    }
    

5. Debugging Logs

  • Missing Logs?
    • Check if the bundle is registered (config/bundles.php or service provider).
    • Verify Doctrine entities are mapped correctly (Laravel’s User must implement UserInterface).
    • Enable Symfony’s debug mode:
      $this->app->booted(function () {
          if ($this->app->environment('local')) {
              $this->app->make('debug')->enable();
          }
      });
      

6. Extending Log Fields

  • Need Custom Data? Override the ActivityLog entity or use Laravel’s accessors:
    // app/Models/ActivityLog.php
    class ActivityLog extends Model {
        protected $casts = [
            'metadata' => 'json',
        ];
    
        public function getIpAttribute($value) {
            return $this->metadata['ip'] ?? $value;
        }
    }
    

7. Security: Sensitive Data

  • Issue: Logs may contain PII (e.g., passwords in request bodies). Fix:
    • Sanitize logs before storage:
      $sanitizedBody = str_replace(['password', 'token'], '[REDA
      
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime