- How do I add blamable fields to an existing Eloquent model in Laravel?
- Use the `Blamable` trait in your model and call `Blamable::blamable()` in the boot method. Run a migration to add `created_by`, `updated_by`, and `deleted_by` fields. For legacy models, backfill data heuristically (e.g., assume the first editor is the creator).
- Does this package work with Laravel Sanctum or Passport for API authentication?
- Yes, but ensure `Auth::user()` resolves correctly in API contexts. If using Sanctum/Passport, verify the auth guard is set properly. For queues/jobs, inject auth context via middleware or manually set the user in the job payload.
- Can I use `laravel-blamable` with soft deletes (SoftDeletes trait)?
- Yes, combine it with `BlamableSoftDeletes` for `deleted_by` tracking. The package automatically handles the `deleted_by` field alongside `deleted_at`. Test in staging first to confirm schema compatibility.
- How does this handle anonymous users or API calls without authentication?
- By default, it sets `created_by`, `updated_by`, or `deleted_by` to `null` if no user is authenticated. For system actions (e.g., cron jobs), manually set a default user via middleware or `Auth::setUser()`.
- Will this work with Laravel 9 or older versions?
- No, it requires Laravel 10+ and PHP 8.1+ due to named arguments in traits. If you’re on an older version, consider forking the package or using a similar solution like `spatie/laravel-activitylog` for partial functionality.
- Does this package track *what* was changed, not just *who*?
- No, it only tracks ownership (who created/updated/deleted). For detailed change history (e.g., field-level modifications), pair it with `spatie/laravel-activitylog` or implement custom observers.
- How do I migrate existing tables to add blamable fields without downtime?
- Use `Schema::table()` in a migration to add nullable foreign keys. For production, backfill data in batches during low-traffic periods. Test the migration in staging first to avoid schema conflicts.
- Can I customize the default user for blamable actions (e.g., system account)?
- Yes, override the `getBlamable()` method in your model or use middleware to set a default user (e.g., `Auth::setUser(User::SYSTEM_ACCOUNT)`). This is useful for automated processes like cron jobs or API webhooks.
- Are there performance concerns with using traits for blamable models?
- No significant overhead—traits add minimal runtime checks. Benchmark in high-write scenarios, but the impact is typically negligible compared to database operations. Avoid excessive joins on `created_by`/`updated_by` in queries.
- What’s the best alternative if I need role-based blaming (e.g., `created_by_role_id`)?
- Extend the `Blamable` trait or fork the package to add role fields. Alternatively, use a package like `spatie/laravel-activitylog` for granular event tracking, though it requires more setup. For simple role tracking, add a `role_id` column alongside `user_id`.