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

Model Traits Bundle Laravel Package

ac/model-traits-bundle

Symfony2 bundle that integrates American Councils’ ac/model-traits into your application, providing reusable model traits and related setup for Symfony projects. Useful for sharing common model behavior across entities with minimal boilerplate.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require american-councils/model-traits-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        AmericanCouncils\ModelTraitsBundle\ModelTraitsBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Use the HasTimestamps trait in a Laravel model (Symfony2 equivalent in Laravel):

    use AmericanCouncils\ModelTraits\HasTimestamps;
    
    class Post extends Model
    {
        use HasTimestamps;
    }
    

    This auto-adds created_at and updated_at columns if they don’t exist.

  3. Where to Look First:

    • Bundle Docs (Symfony2, but Laravel concepts translate).
    • Traits Source for available traits (e.g., HasSoftDeletes, HasSlug, HasUuid).

Implementation Patterns

Core Workflows

  1. Model Boilerplate Reduction: Replace repetitive methods with traits:

    use AmericanCouncils\ModelTraits\HasSlug;
    
    class Product extends Model
    {
        use HasSlug;
    
        protected $slugField = 'name'; // Customize slug source
    }
    

    Automatically generates slugs from name on save.

  2. Soft Deletes:

    use AmericanCouncils\ModelTraits\HasSoftDeletes;
    
    class User extends Model
    {
        use HasSoftDeletes;
        protected $deletedAtColumn = 'deleted_at';
    }
    

    Adds delete() and forceDelete() methods; queries exclude soft-deleted records by default.

  3. UUIDs:

    use AmericanCouncils\ModelTraits\HasUuid;
    
    class Order extends Model
    {
        use HasUuid;
        protected $primaryKey = 'uuid';
    }
    

    Replaces auto-increment IDs with UUIDs; ensure uuid column exists.

  4. Event Hooks: Use HasEvents to trigger custom logic:

    use AmericanCouncils\ModelTraits\HasEvents;
    
    class Comment extends Model
    {
        use HasEvents;
    
        protected static function bootHasEvents()
        {
            static::created(function ($model) {
                // Send notification on creation
            });
        }
    }
    

Integration Tips

  • Database Migrations: For HasTimestamps/HasSoftDeletes, add columns manually or use Laravel’s Schema::table():

    Schema::table('posts', function (Blueprint $table) {
        $table->timestamps(); // For HasTimestamps
        $table->softDeletes(); // For HasSoftDeletes
    });
    
  • Query Scopes: Traits like HasSoftDeletes add global scopes. Override in boot() if needed:

    protected static function bootHasSoftDeletes()
    {
        static::addGlobalScope('active', function (Builder $builder) {
            $builder->whereNull('deleted_at');
        });
    }
    
  • Customization: Override trait methods (e.g., generateSlug() in HasSlug) for business logic.


Gotchas and Tips

Pitfalls

  1. Symfony2 → Laravel Mismatch:

    • The bundle is Symfony2-focused. Laravel’s Eloquent differs in:
      • Query builder methods (e.g., where() vs. Symfony’s createQueryBuilder()).
      • Model bootstrapping (Laravel’s boot() vs. Symfony’s __construct()).
    • Fix: Use traits as inspiration; adapt methods to Laravel’s conventions.
  2. Missing Laravel-Specific Features:

    • No built-in support for Laravel’s Observers, Events, or Accessors/Mutators.
    • Workaround: Combine with Laravel’s native features:
      use HasTimestamps;
      
      class Post extends Model
      {
          use HasTimestamps;
      
          public function getTitleAttribute($value)
          {
              return strtoupper($value); // Mutator
          }
      }
      
  3. Database Column Conflicts:

    • Traits like HasTimestamps assume column names (created_at, updated_at). Override:
      protected $dates = ['custom_created_at', 'custom_updated_at'];
      
  4. Trait Loading Order:

    • Laravel’s boot() runs before traits. Defer trait logic to boot():
      use HasEvents;
      
      protected static function bootHasEvents()
      {
          static::created(function ($model) {
              // Runs after Laravel's boot()
          });
      }
      

Debugging Tips

  • Check Trait Methods: Use php artisan tinker to inspect trait methods:

    $post = new Post();
    get_class_methods($post); // List all methods (including traits)
    
  • Override for Debugging: Temporarily override a trait method to log behavior:

    public function generateSlug()
    {
        \Log::info('Generating slug for: ' . $this->name);
        return parent::generateSlug();
    }
    

Extension Points

  1. Add Custom Traits: Fork the model-traits repo and extend:

    namespace App\Traits;
    
    use AmericanCouncils\ModelTraits\Concerns\HasSlug;
    
    trait HasCustomSlug
    {
        use HasSlug;
    
        public function generateSlug()
        {
            return strtolower(parent::generateSlug());
        }
    }
    
  2. Laravel-Specific Traits: Create Laravel-compatible traits by wrapping Symfony logic:

    trait HasLaravelSoftDeletes
    {
        public static function bootHasSoftDeletes()
        {
            static::addGlobalScope('softDeletes', function (Builder $builder) {
                $builder->whereNull('deleted_at');
            });
        }
    
        public function delete()
        {
            $this->forceFill(['deleted_at' => now()])->save();
        }
    }
    
  3. Configuration: Use Laravel’s config() helper to centralize trait settings:

    // config/traits.php
    return [
        'slug_separator' => '-',
    ];
    
    // In trait:
    $separator = config('traits.slug_separator');
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor