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

digitalcloud/laravel-blameable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require digitalcloud/laravel-blameable
    

    For Laravel <5.5, manually register DigitalCloud\Blameable\BlameableServiceProvider in config/app.php.

  2. Publish Config (optional, but recommended for customization):

    php artisan vendor:publish --provider="DigitalCloud\Blameable\BlameableServiceProvider" --tag="config"
    

    This generates config/blameable.php with default column names (created_by, updated_by, deleted_by) and model mappings.

  3. Apply to a Model: Use the Blameable trait in your Eloquent model:

    use DigitalCloud\Blameable\Blameable;
    
    class Post extends Model
    {
        use Blameable;
    }
    
  4. First Use Case: Authenticate a user (e.g., auth()->user()), then create/update a model. The package auto-populates created_by, updated_by, or deleted_by based on the authenticated user.


Implementation Patterns

Core Workflows

  1. Automatic Tracking:

    • The trait automatically binds created_by, updated_by, and deleted_by to the authenticated user (via Auth::user()).
    • No manual intervention needed for CRUD operations.
  2. Model-Specific Configuration:

    • Override column names in config/blameable.php:
      'column_names' => [
          'createdByAttribute' => 'author_id',
          'updatedByAttribute' => 'last_modified_by',
      ],
      
    • Map custom user models (e.g., Admin instead of User):
      'models' => [
          'admin' => \App\Models\Admin::class,
      ],
      
  3. Manual Overrides: Force a specific user for an operation:

    $post = new Post();
    $post->forceFillUser($user)->save(); // Manually set creator/updater.
    
  4. Soft Deletes: If using SoftDeletes, deleted_by is auto-populated on delete():

    $post->delete(); // Sets `deleted_by` to authenticated user.
    
  5. Query Scopes: Filter models by creator/updater:

    Post::createdBy($user)->get();
    Post::updatedBy($user)->get();
    

Integration Tips

  • Middleware: Use auth middleware to ensure users are authenticated before blameable operations.
  • Events: Listen for creating, updating, or deleted events to log or audit changes:
    Post::created(function ($post) {
        Log::info("Post {$post->id} created by {$post->created_by}");
    });
    
  • APIs: Combine with laravel-api packages to expose blameable fields in responses:
    return new PostResource($post->load('user')); // Show creator details.
    

Gotchas and Tips

Pitfalls

  1. Authentication Dependency:

    • The package relies on Auth::user(). If no user is authenticated, blameable fields will be null.
    • Fix: Use middleware or default values:
      config(['blameable.default_user' => 1]); // Fallback user ID.
      
  2. Column Name Conflicts:

    • If your model already has columns like created_by, the package will overwrite them.
    • Fix: Rename columns in config/blameable.php or add fillable guards:
      protected $fillable = ['title', 'content']; // Exclude blameable columns.
      
  3. Soft Deletes + Blameable:

    • deleted_by only works with SoftDeletes. For hard deletes, manually set the field:
      $post->forceDelete(); // Won't auto-set `deleted_by`.
      $post->deleted_by = auth()->id();
      $post->delete();
      
  4. Model Caching:

    • If using model caching (e.g., Model::newQuery()->get()), blameable attributes may not update in real-time.
    • Fix: Clear cache after updates or avoid caching for blameable models.

Debugging

  • Check Auth: Verify Auth::user() returns the expected user:
    dd(auth()->user()); // Debug during operations.
    
  • Log SQL: Enable Laravel query logging to confirm blameable fields are updated:
    DB::enableQueryLog();
    $post->save();
    dd(DB::getQueryLog());
    
  • Config Validation: Ensure config/blameable.php is correctly published and loaded.

Extension Points

  1. Custom User Resolution: Override the user resolver in the trait:

    use DigitalCloud\Blameable\Concerns\ResolvesUser;
    
    class Post extends Model
    {
        use Blameable, ResolvesUser;
    
        protected function resolveUser()
        {
            return User::find(1); // Custom logic.
        }
    }
    
  2. Dynamic Column Names: Use accessors to dynamically compute blameable fields:

    public function getCreatedByAttribute($value)
    {
        return User::find($value)?->name ?? 'Anonymous';
    }
    
  3. Batch Operations: For bulk updates, manually set blameable fields:

    Post::where('status', 'draft')->update([
        'updated_by' => auth()->id(),
        'status' => 'published',
    ]);
    
  4. Testing: Mock the authenticated user in tests:

    $this->actingAs($user);
    $post = Post::create([...]); // `created_by` will be `$user->id`.
    
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.
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
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament